Spring依賴注入
<b>from:</b>http://linghongli.javaeye.com/blog/591063
Spring依賴注入包含下面三種方式
1.使用構造器注入
2.使用屬性setter方法注入
3.使用Field注入(用于注解方式)
注入依賴對象可以采用手工裝配或自動裝配,在實際應用中建議使用手工裝配,因為自動裝配會産生未知情況,開發人員無法預見最終的裝配結果。
1.手工裝配依賴對象
2.自動裝配依賴對象
下面分别介紹一下這兩種方式
一:手工裝配依賴對象
手工裝配依賴對象,在這種方式中又有兩種程式設計方式:
1. 在xml配置檔案中,通過在bean節點下配置,如
<bean id="orderService" class="cn.itcast.service.OrderServiceBean">
<constructor-arg index=“0” type=“java.lang.String” value=“xxx”/>//構造器注入
<property name=“name” value=“zhao/>//屬性setter方法注入
</bean>
2. 在java代碼中使用@Autowired或@Resource注解方式進行裝配。但我們需要在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>
這個配置隐式注冊了多個對注釋進行解析處理的處理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
注: @Resource注解在spring安裝目錄的lib\j2ee\common-annotations.jar
在java代碼中使用@Autowired或@Resource注解方式進行裝配,這兩個注解的差別是:@Autowired 預設按類型裝配,@Resource預設按名稱裝配,當找不到與名稱比對的bean才會按類型裝配。
@Autowired
private PersonDao personDao;//用于字段上
public void setOrderDao(OrderDao orderDao) {//用于屬性的setter方法上
this.orderDao = orderDao;
}
@Autowired注解是按類型裝配依賴對象,預設情況下它要求依賴對象必須存在,如果允許null值,可以設定它required屬性為false。如果我們想使用按名稱裝配,可以結合@Qualifier注解一起使用。如下:
@Autowired @Qualifier("personDaoBean")
private PersonDao personDao;
@Resource注解和@Autowired一樣,也可以标注在字段或屬性的setter方法上,但它預設按名稱裝配。名稱可以通過@Resource的name屬性指定,如果沒有指定name屬性,當注解标注在字段上,即預設取字段的名稱作為bean名稱尋找依賴對象,當注解标注在屬性的setter方法上,即預設取屬性名作為bean名稱尋找依賴對象。
@Resource(name=“personDaoBean”)
注意:如果沒有指定name屬性,并且按照預設的名稱仍然找不到依賴對象時, @Resource注解會回退到按類型裝配。但一旦指定了name屬性,就隻能按名稱裝配了。
二:自動裝配依賴對象
對于自動裝配,大家了解一下就可以了,實在不推薦大家使用。例子:
<bean id="..." class="..." autowire="byType"/>
autowire屬性取值如下:
byType:按類型裝配,可以根據屬性的類型,在容器中尋找跟該類型比對的bean。如果發現多個,那麼http://linghongli.javaeye.com/admin/blogs/new#将會抛出異常。如果沒有找到,即屬性值為null。
byName:按名稱裝配,可以根據屬性的名稱,在容器中尋找跟該屬性名相同的bean,如果沒有找到,即屬性值為null。
constructor與byType的方式類似,不同之處在于它應用于構造器參數。如果在容器中沒有找到與構造器參數類型一緻的bean,那麼将會抛出異常。
autodetect:通過bean類的自省機制(introspection)來決定是使用constructor還是byType方式進行自動裝配。如果發現預設的構造器,那麼将使用byType方式。