在java代碼中使用@Autowired或@Resource註解方式進行裝配的前提條件是。
1、引入context命名空間 需要在xml配置文件中配置以下信息:
<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>
2、在配置文件中添加context:annotation-config標籤
<context:annotation-config/>
這個配置隱式註冊了多個對註釋進行解析處理的處理器
AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,
PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
注:@Resource註解在spring安裝目錄的lib\j2ee\common-annotations.jar 在java代碼中使用@Autowired或@Resource註解方式進行裝配,這兩個註解的區別是:@Autowired默認按類型裝配,@Resource默認按名稱裝配,當找不到與名稱匹配的bean纔會按類型裝配。 @Autowired
private PersonDao personDao;//用於字段上
@Autowired
public void setPersonDao(PersonDao personDao) { //用於屬性的set方法上
this.personDao = personDao;
}
@Autowired註解是按類型裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它required屬性爲false。
@Autowired(required=false)
private PersonDao personDao;//用於字段上
@Autowired(request=false)
public void setPersonDao(PersonDao personDao) { //用於屬性的set方法上
this.personDao = personDao;
} 如果我們想使用按名稱裝配,可以結合@Qualifier註解一起使用。如下:
@Autowired @Qualifier("personDao")
private PersonDao personDao;//用於字段上
@Autowired
public void setPersonDao(@Qualifier("personDao") PersonDao personDao) {//用於屬性的set方法上
this.personDao = personDao;
} @Qualifier註解也能夠被指定爲構造器的參數或者方法的參數:
@Resource註解和@Autowired一樣,也可以標註在字段或屬性的setter方法上.
@Resource註解默認按名稱裝配。
名稱可以通過@Resource的name屬性指定,如果沒有指定name屬性,
•當註解標註在字段上,即默認取字段的名稱作爲bean名稱尋找依賴對象
•當註解標註在屬性的setter方法上,即默認取屬性名作爲bean名稱尋找依賴對象。
@Resource(name="personDao")
private PersonDao personDao;;//用於字段上
@Resource(name="personDao")
public void setPersonDao(PersonDao personDao){//用於屬性的set方法上
this.personDao = personDao;
}
後一種相當於xml配置文件中的
<property name=“personDao" ref="personDao" />
注意:如果沒有指定name屬性,並且按照默認的名稱找不到依賴對象時,@Resource註解會回退到按類型裝配。但一旦指定了name屬性,就只能按名稱裝配了。
本文由ROSE收集整理 |
spring手工裝配 條件
spring依賴注入--手工裝配—註解方式
2011-03-21 22:47
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.