spring注解说明之Spring2.5 注解介绍(3.0通用)

spring注解说明之Spring2.5 注解介绍(3.0通用)

注册注解处理器  

方式一:bean
  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
方式二:命名空间
  <context:annotation-config /><context:annotationconfig />
  将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
  PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor这4 个BeanPostProcessor。
方式三:命名空间
  <context:component-scan />
  若是要使注解工做,则必须配置component-scan,实际上不须要再配置annotation-config。base-package属性指定了须要扫描的类包,
  类包及其递归子包中全部的类都会被处理。还容许定义过滤器将基包下的某些类归入或排除。java

Spring支持如下4种类型的过滤方式

  1)注解 org.example.SomeAnnotation将全部使用SomeAnnotation注解的类过滤出来
  2)类名指定: org.example.SomeClass过滤指定的类
  3)正则表达式: com.kedacom.spring.annotation.web..* 经过正则表达式过滤一些类
  4)AspectJ: 表达式 org.example..*Service+ 经过AspectJ 表达式过滤一些类web


  正则表达式的过滤方式举例:

    <context:component-scanbase-package="com.casheen.spring.annotation">
      <context:exclude-filtertype="regex" expression="com.casheen.spring.annotation.web..*"/>
    </context:component-scan>ajax

  注解的过滤方式举例:

    <context:component-scan base-package="com.netqin" >
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>正则表达式

启用Spring MVC 注解

  启动Spring MVC的注解功能,完成请求和注解POJO的映射spring

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>express

请求处理方法返回值的可选类型

void 
        此时逻辑视图名由请求处理方法对应的 URL肯定,如如下的方法:
            @RequestMapping("/welcome.do")
            public void welcomeHandler() {}
            对应的逻辑视图名为 'welcome' 
    String
        此时逻辑视图名为返回的字符,如如下的方法:
            @RequestMapping(method = RequestMethod.GET)
                public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
                Owner owner = this.clinic.loadOwner(ownerId);
                model.addAttribute(owner);
                return "ownerForm";
            }
              对应的逻辑视图名为 “ ownerForm ” 
    org.springframework.ui.ModelMap
        和返回类型为 void同样,逻辑视图名取决于对应请求的 URL,以下面的例子:
            @RequestMapping("/vets.do")
            public ModelMap vetsHandler() {
                return new ModelMap(this.clinic.getVets());
            }
            对应的逻辑视图名为'vets',返回的ModelMap将被做为请求对应的模型对象,能够在JSP视图页面中访问到。
    ModelAndView
        固然还能够是传统的 ModelAndView.

 

@Controller

  例如
    @Controller
    public class SoftCreateController extends SimpleBaseController {}
  或者
    @Controller("softCreateController")
  说明
    @Controller负责注册一个bean到spring上下文中,bean的ID默认为类名称开头字母小写

 @Service

  例如
      @Service
      public class SoftCreateServiceImpl implements ISoftCreateService {}
  或者
      @Service("softCreateServiceImpl")
  说明
      @Service负责注册一个bean到spring上下文中,bean的ID默认为类名称开头字母小写

@Autowired

    例如
        @Autowired
        private ISoftPMService softPMService;
    或者
        @Autowired(required=false)
        private ISoftPMService softPMService = new SoftPMServiceImpl();
    说明
        @Autowired根据bean类型从spring上下文中进行查找,注册类型必须惟一,不然报异常。
        与@Resource 的区别在于,@Resource容许经过bean名称或bean类型两种方式进行查找@Autowired(required=false)表示.
        若是spring上下文中没有找到该类型的bean时,才会使用new SoftPMServiceImpl();@Autowired标注做用于 Map类型时,
        若是 Map的 key为 String类型,则 Spring会将容器中全部类型符合 Map的 value对应的类型的 Bean增长进来,用Bean的 id或 name做为 Map的 key。
        @Autowired还有一个做用就是,若是将其标注在 BeanFactory、ApplicationContext、ResourceLoader、ApplicationEventPublisher、MessageSource类型上,
        那么 Spring会自动注入这些实现类的实例,不须要额外的操做。 

@RequestMapping

    类注解
        @Controller 
        @RequestMapping("/bbtForum.do")
        public class BbtForumController {
            @RequestMapping(params = "method=listBoardTopic")
            public String listBoardTopic(int topicId,User user) {}
        }
    方法注解
        @RequestMapping("/softpg/downSoftPg.do")
        @RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)
        @RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)
    说明
        @RequestMapping能够声明到类或方法上
    参数绑定说明,若是咱们使用如下的 URL请求:
        例:http://localhost/bbtForum.domethod=listBoardTopic&topicId=1&userId=10&userName=tom
              topicId URL 参数将绑定到 topicId入参上,
            而 userId 和 userName URL 参数将绑定到 user对象的 userId和 userName属性中。
            和 URL请求中不容许没有 topicId参数不一样,虽然 User的 userId属性的类型是基本数据类型,但若是 URL中不存在 userId 参数,
            Spring也不会报错,此时 user.userId值为 0 。若是 User对象拥有一个 dept.deptId的级联属性,那么它将和 dept.deptId URL参数绑定。

@RequestParam

  参数绑定说明
    @RequestParam("id")
    http://localhost/bbtForum.domethod=listBoardTopic&id=1&userId=10&userName=tom
        listBoardTopic(@RequestParam("id")int topicId,User user)中的 topicId绑定到 id这个 URL参数,那么能够经过对入参使用 @RequestParam注解来达到目的
    @RequestParam(required=false):参数不是必须的,默认为true
    @RequestParam(value="id",required=false)
    
    请求处理方法入参的可选类型Java基本数据类型和 String
    默认状况下将按名称匹配的方式绑定到 URL参数上,能够经过 @RequestParam注解改变默认的绑定规则
    
    request/response/session既能够是 Servlet API的也能够是 Portlet API对应的对象,Spring会将它们绑定到Servlet和 Portlet容器的相应对象上
    
    org.springframework.web.context.request.WebRequest内部包含了request对象
    java.util.Locale绑定到 request对应的 Locale对象上
    java.io.InputStream/java.io.Reader能够借此访问request的内容
    java.io.OutputStream/java.io.Writer能够借此操做 response 的内容
          任何被标注 @RequestParam注解的入参将绑定到特定的request参数上。
    java.util.Map/org.springframework.ui.ModelMap它绑定Spring MVC框架中每一个请求所建立的潜在的模型对象,它们能够被 Web视图对象访问(如SP)
          命令/表单对象(注:通常称绑定使用 HTTP GET发送的 URL参数的对象为命令对象,而称绑定使用HTTP POST发送的 URL参数的对象为表单对象)它们的属性将以名称匹配的规则绑定到 URL参数上,同时完成类型的转换。
           而类型转换的规则能够经过 @InitBinder注解或经过 HandlerAdapter的配置进行调整
    org.springframework.validation.Errors/org.springframework.validation.BindingResult为属性列表中的命令/表单对象的校验结果,注意检验结果参数必须紧跟在命令/表单对象的后面
    org.springframework.web.bind.support.SessionStatus能够经过该类型 status对象显式结束表单的处理,这至关于触发 session清除其中的经过@SessionAttributes定义的属性
    
    

@ModelAttribute

  做用域:request
    例如
        @RequestMapping("/base/userManageCooper/init.do")
        public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){
    或者
        @ModelAttribute("coopMap")// 将coopMap 返回到页面
        public Map<Long,CooperatorInfo> coopMapItems(){}
    说明
        @ModelAttribute声明在属性上,表示该属性的value来源于model里"queryBean",并被保存到model里@ModelAttribute声明在方法上,表示该方法的返回值被保存到model里

@Cacheable和@CacheFlush

  @Cacheable:声明一个方法的返回值应该被缓存。例如:@Cacheable(modelId = "testCaching")
  @CacheFlush:声明一个方法是清空缓存的触发器。例如:@CacheFlush(modelId = "testCaching")
    说明
        要配合缓存处理器使用,参考: http://hanqunfeng.iteye.com/blog/603719
        spring3.0没有对缓存提供支持,不过3.1以后就有了,能够参考:Spring3.1 Cache注解

@Resource

    例如
        @Resource
        private DataSource dataSource; // inject the bean named 'dataSource'
    或者
        @Resource(name="dataSource")
        @Resource(type=DataSource.class)
    说明
        @Resource默认按bean的name进行查找,若是没有找到会按type进行查找,此时与@Autowired相似.在没有为 @Resource注解显式指定 name属性的前提下,
        若是将其标注在 BeanFactory、ApplicationContext、ResourceLoader、ApplicationEventPublisher、MessageSource类型上,
        那么Spring会自动注入这些实现类的实例,不须要额外的操做。此时 name属性不须要指定 (或者指定为""),不然注入失败.

@PostConstruct

    在方法上加上注解@PostConstruct,这个方法就会在Bean初始化以后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean 的属性(依赖注入))。
    @PreDestroy
        在方法上加上注解@PreDestroy,这个方法就会在Bean被销毁前被Spring容器执行。
    @Repository
         与@Controller、@Service相似,都是向spring上下文中注册bean,不在赘述。

@Component(不推荐使用)

    @Component是全部受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式: 
    @Repository、@Service、@Controller它们分别对应存储层Bean,业务层Bean,和展现层Bean.
    版本(2.5)中,这些注解与@Component的语义是同样的,彻底通用,在Spring之后的版本中可能会给它们追加更多的语义.
    因此,咱们推荐使用@Repository、@Service、@Controller来替代@Component。

@Scope

    例如
    @Scope("session")
    @Repository
    public class UserSessionBean implementsSerializable {}
    说明
        在使用XML定义Bean时,能够经过bean的scope属性来定义一个Bean的做用范围,一样能够经过@Scope注解来完成,@Scope中能够指定以下值:
            singleton:定义bean的范围为每一个spring容器一个实例(默认值)
            prototype:定义bean能够被屡次实例化(使用一次就建立一次)
            request:定义bean的范围是http请求(springMVC中有效)
            session:定义bean的范围是http会话(springMVC中有效)
            global-session:定义bean的范围是全局http会话(portlet中有效)

@SessionAttributes

    说明
        Spring容许咱们有选择地指定 ModelMap中的哪些属性须要转存到 session中,以便下一个请求属对应的 ModelMap的属性列表中还能访问到这些属性。
        这一功能是经过类定义处标注 @SessionAttributes注解来实现的.
        @SessionAttributes只能声明在类上,而不能声明在方法上.
    例如
        @SessionAttributes("currUser") //将ModelMap中属性名为currUser的属性保存到session
        @SessionAttributes({"attr1","attr2"})
        @SessionAttributes(types = User.class)
        @SessionAttributes(types = {User.class,Dept.class})
        @SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})
@InitBinder
    说明
    若是但愿某个属性编辑器仅做用于特定的 Controller,能够在 Controller中定义一个标注 @InitBinder注解的方法
    也能够在该方法中向 Controller了注册若干个属性编辑器
    例如
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
        }

@Required

    例如
        @required              
        public setName(String name){} 
    说明
        @required负责检查一个bean在初始化时其声明的set方法是否被执行,当某个被标注了@Required的 Setter方法没有被调用,
        则 Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置. @Required注解只能标注在 Setter方法之上。
        由于依赖注入的本质是检查 Setter方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。
        若是将该注解标注在非setXxxx()类型的方法则被忽略。

@Qualifier

    例如
        @Autowired
        @Qualifier("softService")
        private ISoftPMService softPMService;
    说明
        使用@Autowired时,若是找到多个同一类型的bean,则会抛异常,此时可使用 @Qualifier("beanName"),明确指定bean的名称进行注入
        此时与 @Resource指定name属性做用相同。
相关文章
相关标签/搜索