spring中autowire的用法

Autowire模式就是在spring的聲明文件裏用作進行對象間的關聯關係自動綁定的,就是在spring beanfactory內的一個bean對其bean的引用可以自動進行,而不一定用ref=的方式顯式聲明。在reference的3.3.6節有詳細的介紹,autowire主要有5種模式:

 

1 no

不使用Autowire,引用關係顯示聲明,spring的reference也建議不用autoware,因爲這會破壞模塊關係的可讀性,原文如下:

Note: as has already been mentioned, for larger applications, it is discouraged to use autowiring because it

removes the transparency and the structure from your collaborating classes.

 

2 byName

用名稱關聯,如果指定了這種模式,如

   <bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" autowire="byName">

       <property name="baseDAO"/>

   </bean>

這樣對於bean userManagerTarget的屬性baseDAO,spring就會自動去引用同名的bean,也就是上面的聲明和下面是等價的:

   <bean id="userManagerTarget" class="com.mdcchina.jianghu.logic.UserManager" autowire="no">

       <property name="baseDAO">

          <ref local="baseDAO"/>

       </property>

   </bean>

 

3 byType

和前面的byName類似的,就是這個屬性會在整個beanFactory定義裏找和這個屬性一樣的bean自動關聯上,如果有2個或更多這個類型的bean在beanFactory的定義裏,就直接拋異常了,如果沒有,就什麼都不發生,這個屬性就是null,所以這個只適用與這個屬性的類型有且只有一個同類的bean在spring裏定義

 

4 constructor

這個的意思我沒有確定的把握,不過感覺用途也不會大,好像是用構造函數新建一個屬性類型的bean並關聯上,reference原文是:

This is analogous to byType, but applies to constructor arguments. If there isn't exactly one

bean of the constructor argument type in the bean factory, a fatal error is raised.

 

5 autodetect

這個的意思好像是說自動決定用byType還是constructor方式,原文如下:

Chooses constructor or byType through introspection of the bean class. If a default

constructor is found, byType gets applied.

 

綜上所述,感覺上只有byName比較實用一些,但是spring的reference還是不推薦在定義中用這個功能

發佈了13 篇原創文章 · 獲贊 54 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章