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屬性做用相同。
相關文章
相關標籤/搜索