用@Resource注解完成屬性裝配


使用Field注入(用於注解方式):注入依賴對象可以采用手工裝配或者手工自動裝配。在實際應用中建議使用手工裝配,因為自動裝配會產生未知情況,開發人員無法預見最終的裝配結果。

依賴注入—手工裝配

手工裝配依賴對象,在這種方式中又有兩種編程方式。

1.在xml配置文件中,通過bean節點配置,如:

1 <bean id="orderService" class="cn.itcast.service.OrderServiceBean">
2     //構造器注入
3     <constructor-arg index="0" type="java.lang.String" value="xxx"/>
4     //屬setter方法注入
5     <property name="name" value="zhao"/>
6 </bean>

2.在java代碼中使用@Autowired或者@Resource注解方式進行裝配。但我們需要在xml配置文件中配置一下信息

1  <beans Xmlns="http://www.springframework.org/schema/beans"
2              Xmlns="http://www.w3.org/2001/XMLSchema-instance"
3              Xmlns:context="http://www.springframework.org/schema/context"
4              Xsi:schemaLocation="http://www.springframework.org/schema/beans
5                          http://www.springframework.org/schema/context
6                          http://www.springframework.org/schema/context/spring-context-2.5xsd">
7 </beans>  

這個配置隱式注冊了多個對注釋進行解析處理的處理器:
AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor

PersistenceAnnotationBeanProcessor,RequiredAnnotationBeanPostProcessor

3.區別

在java代碼中使用@Autowired或@Resource注解方式進行裝配。這兩個注解的區別是@Autowired默認按類型裝配@Resource默認按名稱進行裝配,當找不到與名稱匹配的bean才會按類型裝配

1 @Autowired
2 private PersonDao personDao;//用於字段上
3 @Autowired
4 public void setOrderDao(OrderDao orderDao){
5        this.orderDao = orderDao; //用於屬性的setter方法上      
6 }

@Autowired注解是按類型裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它required屬性為false;如果我們想使用名稱裝配,可以結合@Qualfier注解一起使用,如下:

@Autowired@Qualifier("personDao")
private PersonDao personDao;

@Resource注解和@Autowired一樣,可以標注在字段或者屬性的setter方法上,但它默認按名稱裝配。名稱可以通過@Resource的name屬性指定;如果沒有指定name屬性,當注解標注在字段上,即默認字段的名稱作為bean名稱尋找依賴對象;當注解標注在屬性setter方法上,即默認取屬性名作為bean名稱尋找依賴對象

@Resource(name="personDaoBean")
private PersonDao personDao;

注:如果沒有指定name屬性,並且按照默認的名稱仍找不到對象時,@Resource注解會回退到按類型裝配。但一旦指定了name屬性,就只能按名稱裝配了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM