詳解Java的Spring架構中的註解的用法

來源:互聯網
上載者:User

標籤:tor   his   通過   屬性   frame   setter   spring註解   自己   規範   

轉載:http://www.jb51.net/article/75460.htm

 

1. 使用Spring註解來注入屬性

1.1. 使用註解以前我們是怎樣注入屬性的 
類的實現:

class UserManagerImpl implements UserManager {   private UserDao userDao;   public void setUserDao(UserDao userDao) {     this.userDao = userDao;   }   ... }

設定檔:

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">   <property name="userDao" ref="userDao" /> </bean> <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">   <property name="sessionFactory" ref="mySessionFactory" /> </bean>

1.2. 引入@Autowired註解(不推薦使用,建議使用@Resource) 
類的實現(對成員變數進行標註)

public class UserManagerImpl implements UserManager {   @Autowired   private UserDao userDao;   ... }

或者(對方法進行標註)

UserManagerImpl implements UserManager {   private UserDao userDao;   @Autowired   public void setUserDao(UserDao userDao) {     this.userDao = userDao;   }   ... }

設定檔

<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" /> <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">   <property name="sessionFactory" ref="mySessionFactory" /> </bean>

@Autowired可以對成員變數、方法和建構函式進行標註,來完成自動裝配的工作。以上兩種不同實現方式中,@Autowired的標註位置不同,它們都會在Spring在初始化userManagerImpl這個bean時,自動裝配userDao這個屬性,區別是:第一種實現中,Spring會直接將UserDao類型的唯一一個bean賦值給userDao這個成員變數;第二種實現中,Spring會調用setUserDao方法來將UserDao類型的唯一一個bean裝配到userDao這個屬性。

1.3. 讓@Autowired工作起來 
要使@Autowired能夠工作,還需要在設定檔中加入以下代碼

class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

1.4. @Qualifier 
@Autowired是根據類型進行自動裝配的。在上面的例子中,如果當Spring上下文中存在不止一個UserDao類型的bean時,就會拋出BeanCreationException異常;如果Spring上下文中不存在UserDao類型的bean,也會拋出BeanCreationException異常。我們可以使用@Qualifier配合@Autowired來解決這些問題。 
1. 可能存在多個UserDao執行個體

@Autowired public void setUserDao(@Qualifier("userDao") UserDao userDao) {   this.userDao = userDao; }

這樣,Spring會找到id為userDao的bean進行裝配。 
2. 可能不存在UserDao執行個體

@Autowired(required = false) public void setUserDao(UserDao userDao) {   this.userDao = userDao; } 

1.5. @Resource(JSR-250標準註解,推薦使用它來代替Spring專有的@Autowired註解) 
Spring 不但支援自己定義的@Autowired註解,還支援幾個由JSR-250規範定義的註解,它們分別是@Resource、@PostConstruct以及@PreDestroy。 
@Resource的作用相當於@Autowired,只不過@Autowired按byType自動注入,而@Resource預設按byName自動注入罷了。@Resource有兩個屬性是比較重要的,分別是name和type,Spring將@Resource註解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。 
@Resource裝配順序

如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則拋出異常
如果指定了name,則從上下文中尋找名稱(id)匹配的bean進行裝配,找不到則拋出異常
如果指定了type,則從上下文中找到類型匹配的唯一bean進行裝配,找不到或者找到多個,都會拋出異常
如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配(見2);如果沒有匹配,則回退為一個原始類型(UserDao)進行匹配,如果匹配則自動裝配;
1.6. @PostConstruct(JSR-250) 
在方法上加上註解@PostConstruct,這個方法就會在Bean初始化之後被Spring容器執行(註:Bean初始化包括,執行個體化Bean,並裝配Bean的屬性(依賴注入))。 
它的一個典型的應用情境是,當你需要往Bean裡注入一個其父類中定義的屬性,而你又無法複寫父類的屬性或屬性的setter方法時,如: 

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {   private SessionFactory mySessionFacotry;   @Resource   public void setMySessionFacotry(SessionFactory sessionFacotry) {     this.mySessionFacotry = sessionFacotry;   }   @PostConstruct   public void injectSessionFactory() {     super.setSessionFactory(mySessionFacotry);   }   ... }

這裡通過@PostConstruct,為UserDaoImpl的父類裡定義的一個sessionFactory私人屬性,注入了我們自己定義的sessionFactory(父類的setSessionFactory方法為final,不可複寫),之後我們就可以通過調用super.getSessionFactory()來訪問該屬性了。


1.7. @PreDestroy(JSR-250) 
在方法上加上註解@PreDestroy,這個方法就會在Bean初始化之後被Spring容器執行。由於我們當前還沒有需要用到它的情境,這裡不不去示範。其用法同@PostConstruct。

1.8. 使用<context:annotation-config />簡化配置 
Spring2.1添加了一個新的context的Schema命名空間,該命名空間對注釋驅動、屬性檔案引入、載入期織入等功能提供了便捷的配置。我們知道注釋本身是不會做任何事情的,它僅提供中繼資料資訊。要使中繼資料資訊真正起作用,必須讓負責處理這些中繼資料的處理器工作起來。 
AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是處理這些注釋中繼資料的處理器。但是直接在Spring設定檔中定義這些Bean顯得比較笨拙。Spring為我們提供了一種方便的註冊這些BeanPostProcessor的方式,這就是<context:annotation-config />:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"   xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd">   <context:annotation-config /> </beans>

<context:annotationconfig />將隱式地向Spring容器註冊AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor這4個BeanPostProcessor。

2. 使用Spring註解完成Bean的定義 
以上我們介紹了通過@Autowired或@Resource來實現在Bean中自動注入的功能,下面我們將介紹如何註解Bean,從而從XML設定檔中完全移除Bean定義的配置。

2.1. @Component(不推薦使用)、@Repository、@Service、@Controller 
只需要在對應的類上加上一個@Component註解,就將該類定義為一個Bean了:

@Component public class UserDaoImpl extends HibernateDaoSupport implements UserDao {   ... }

使用@Component註解定義的Bean,預設的名稱(id)是小寫開頭的非限定類名。如這裡定義的Bean名稱就是userDaoImpl。你也可以指定Bean的名稱: 
@Component("userDao") 
@Component是所有受Spring管理組件的通用形式,Spring還提供了更加細化的註解形式:@Repository、@Service、@Controller,它們分別對應儲存層Bean,業務層Bean,和展示層Bean。目前版本(2.5)中,這些註解與@Component的語義是一樣的,完全通用,在Spring以後的版本中可能會給它們追加更多的語義。所以,我們推薦使用@Repository、@Service、@Controller來替代@Component。

2.2. 使用<context:component-scan />讓Bean定義註解工作起來

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"   xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd">   <context:component-scan base-package="com.kedacom.ksoa" /> </beans>

這裡,所有通過<bean>元素定義Bean的配置內容已經被移除,僅需要添加一行<context:component-scan />配置就解決所有問題了——Spring XML設定檔得到了極致的簡化(當然配置中繼資料還是需要的,只不過以注釋形式存在罷了)。<context:component-scan />的base-package屬性指定了需要掃描的類包,類包及其遞迴子包中所有的類都會被處理。 
<context:component-scan />還允許定義過濾器將基包下的某些類納入或排除。Spring支援以下4種類型的過濾方式:

過濾器類型 運算式範例 說明
註解 org.example.SomeAnnotation 將所有使用SomeAnnotation註解的類過濾出來
類名指定 org.example.SomeClass 過濾指定的類
Regex com\.kedacom\.spring\.annotation\.web\..* 通過Regex過濾一些類
AspectJ運算式 org.example..*Service+ 通過AspectJ運算式過濾一些類

以Regex為例,我列舉一個應用執行個體:

<context:component-scan base-package="com.casheen.spring.annotation">   <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" /> </context:component-scan>

值得注意的是<context:component-scan />配置項不但啟用了對類包進行掃描以實施注釋驅動Bean定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部註冊了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),因此當使用<context:component-scan />後,就可以將<context:annotation-config />移除了。

2.3. 使用@Scope來定義Bean的作用範圍 
在使用XML定義Bean時,我們可能還需要通過bean的scope屬性來定義一個Bean的作用範圍,我們同樣可以通過@Scope註解來完成這項工作:

@Scope("session") @Component() public class UserSessionBean implements Serializable {   ... }

3.在使用annotation之前定義三個bean之間的關係是這樣的

package com.baobaotao;public class Office {  private String officeNo =”001”;   //省略 get/setter   @Override  public String toString() {    return "officeNo:" + officeNo;  }}ackage com.baobaotao; public class Car {  private String brand;  private double price;   // 省略 get/setter   @Override  public String toString() {    return "brand:" + brand + "," + "price:" + price;  }}package com.baobaotao; public class Boss {  private Car car;  private Office office;   // 省略 get/setter   @Override  public String toString() {    return "car:" + car + "\n" + "office:" + office;  }}

設定檔如下:

<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  <bean id="boss" class="com.baobaotao.Boss">    <property name="car" ref="car"/>    <property name="office" ref="office" />  </bean>  <bean id="office" class="com.baobaotao.Office">    <property name="officeNo" value="002"/>  </bean>  <bean id="car" class="com.baobaotao.Car" scope="singleton">    <property name="brand" value=" 紅旗 CA72"/>    <property name="price" value="2000"/>  </bean></beans>

測試檔案如下:

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class AnnoIoCTest {   public static void main(String[] args) {    String[] locations = {"beans.xml"};    ApplicationContext ctx =       new ClassPathXmlApplicationContext(locations);    Boss boss = (Boss) ctx.getBean("boss");    System.out.println(boss);  }}

 
4.接下來我們可以使用autowired來註解,他可以對成員變數,方法及建構函式進行標準,完成自動裝配的工作。

autoware來註解成員變數的用法

package com.baobaotao;import org.springframework.beans.factory.annotation.Autowired; public class Boss {   @Autowired  private Car car;   @Autowired  private Office office;   …}

相應的設定檔如下:

<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">   <!-- 該 BeanPostProcessor 將自動起作用,對標註 @Autowired 的 Bean 進行自動注入 -->  <bean class="org.springframework.beans.factory.annotation.    AutowiredAnnotationBeanPostProcessor"/>   <!-- 移除 boss Bean 的屬性注入配置的資訊 -->  <bean id="boss" class="com.baobaotao.Boss"/>   <bean id="office" class="com.baobaotao.Office">    <property name="officeNo" value="001"/>  </bean>  <bean id="car" class="com.baobaotao.Car" scope="singleton">    <property name="brand" value=" 紅旗 CA72"/>    <property name="price" value="2000"/>  </bean></beans>

autoware也可以用在setter方法及建構函式上

package com.baobaotao; public class Boss {  private Car car;  private Office office;    @Autowired  public void setCar(Car car) {    this.car = car;  }   @Autowired  public void setOffice(Office office) {    this.office = office;  }  …}package com.baobaotao; public class Boss {  private Car car;  private Office office;   @Autowired  public Boss(Car car ,Office office){    this.car = car;    this.office = office ;  }   …}

當候選bean的數目為0時,我們可以使用@Autowired(required = false)來防止spring找不到bean時報錯。

當有多個候選bean的時候,我們可以通過@Qualifier 注釋指定注入 Bean 的名稱。

@Autowired 和 @Qualifier 結合使用時,自動注入的策略就從 byType 轉變成 byName 了。@Autowired 可以對成員變數、方法以及建構函式進行注釋,而 @Qualifier 的標註對象是成員變數、方法入參、建構函式入參。正是由於注釋對象的不同,所以 Spring 不將 @Autowired 和 @Qualifier 統一成一個注釋類。

[email protected]是按照名字來進行反射,他有兩個參數,name和type,使用name即按照byname來映射,使用type即按照bytype來進行映射。

package com.baobaotao; import javax.annotation.Resource; public class Boss {  // 自動注入類型為 Car 的 Bean  @Resource  private Car car;   // 自動注入 bean 名稱為 office 的 Bean  @Resource(name = "office")  private Office office;}@postconstructor和preDestory是用來註解類初始化後和銷毀前的方法。 package com.baobaotao; import javax.annotation.Resource;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy; public class Boss {  @Resource  private Car car;   @Resource(name = "office")  private Office office;   @PostConstruct  public void postConstruct1(){    System.out.println("postConstruct1");  }   @PreDestroy  public void preDestroy1(){    System.out.println("preDestroy1");   }  …}

[email protected]可以直接定義bean,這樣xml設定檔中就不需要配置bean了

package com.baobaotao; import org.springframework.stereotype.Component; @Componentpublic class Car {  …}package com.baobaotao; import org.springframework.stereotype.Component; @Componentpublic class Office {  private String officeNo = "001";  …}package com.baobaotao; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Required;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Component; @Component("boss")public class Boss {  @Autowired  private Car car;   @Autowired  private Office office;  …}

@Component 有一個可選的入參,用於指定 Bean 的名稱,在 Boss 中,我們就將 Bean 名稱定義為“boss”。一般情況下,Bean 都是 singleton 的,需要注入 Bean 的地方僅需要通過 byType 策略就可以自動注入了,所以大可不必指定 Bean 的名稱。

<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context="http://www.springframework.org/schema/context"  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd">  <context:component-scan base-package="com.baobaotao"/></beans>

[email protected]可以用來指定其目標

package com.baobaotao;import org.springframework.context.annotation.Scope;…@Scope("prototype")@Component("boss")public class Boss {


Spring 2.5 中除了提供 @Component 注釋外,還定義了幾個擁有特殊語義的注釋,它們分別是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,這 3 個注釋和 @Component 是等效的,但是從注釋類的命名上,很容易看出這 3 個注釋分別和持久層、業務層和控制層(Web 層)相對應。雖然目前這 3 個注釋和 @Component 相比沒有什麼新意,但 Spring 將在以後的版本中為它們添加特殊的功能。所以,如果 Web 應用程式採用了經典的三層分層結構的話,最好在持久層、業務層和控制層分別採用 @Repository、@Service 和 @Controller 對分層中的類進行注釋,而用 @Component 對那些比較中立的類進行注釋。

 

詳解Java的Spring架構中的註解的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.