Spring(6)---自動裝配Beans
Spring自動裝配Beans
在Spring框架,可以用 auto-wiring 功能會自動裝配Bean。要啟用它,只需要在 <bean>定義“autowire”屬性。
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" />
在Spring中,支援 5 自動裝配模式。
- no – 預設情況下,自動配置是通過“ref”屬性手動設定
- byName – 根據屬性名稱自動裝配。如果一個bean的名稱和其他bean屬性的名稱是一樣的,將會自裝配它。
- byType – 按資料型別自動裝配。如果一個bean的資料型別是用其它bean屬性的資料型別,相容並自動裝配它。
- constructor – 在建構函式引數的byType方式。
- autodetect – 如果找到預設的建構函式,使用“自動裝配用構造”; 否則,使用“按型別自動裝配”。
示例
Customer 和 Person 物件自動裝配示範。
package com.yiibai.common; public class Customer { private Person person; public Customer(Person person) { this.person = person; } public void setPerson(Person person) { this.person = person; } //... }
package com.yiibai.common; public class Person { //... }
1. Auto-Wiring ‘no’
這是預設的模式,你需要通過 'ref' 屬性來連線 bean。
<bean id="customer" class="com.yiibai.common.Customer"> <property name="person" ref="person" /> </bean> <bean id="person" class="com.yiibai.common.Person" />
2. Auto-Wiring ‘byName’
按屬性名稱自動裝配。在這種情況下,由於對“person” bean的名稱是相同於“customer” bean 的屬性(“person”)名稱,所以,Spring會自動通過setter方法將其裝配 – “setPerson(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="person" class="com.yiibai.common.Person" />
檢視完整的示例 – Spring按名稱自動裝配
3. Auto-Wiring ‘byType’
通過按屬性的資料型別自動裝配Bean。在這種情況下,由於“Person” bean中的資料型別是與“customer” bean的屬性(Person物件)的資料型別一樣的,所以,Spring會自動通過setter方法將其自動裝配。– “setPerson(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="byType" /> <bean id="person" class="com.yiibai.common.Person" />
檢視完整的示例 – Spring通過型別自動裝配
4. Auto-Wiring ‘constructor’
通過建構函式引數的資料型別按屬性自動裝配Bean。在這種情況下,由於“person” bean的資料型別與“customer” bean的屬性(Person物件)的建構函式引數的資料型別是一樣的,所以,Spring通過構造方法自動裝配 – “public Customer(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="constructor" /> <bean id="person" class="com.yiibai.common.Person" />
檢視完整的示例 –
檢視完整的示例 – Spring按AutoDetect自動裝配成功.
注
這是一件好事,這兩個auto-wire’ 和 ‘dependency-check’ 相結合,以確保屬性始終自動裝配成功。
<bean id="customer" class="com.yiibai.common.Customer" autowire="autodetect" dependency-check="objects /> <bean id="person" class="com.yiibai.common.Person" />
結論
在我看來,Spring ‘auto-wiring’ 以極大的成本做出更快開發效率 - 它增加了對整個 bean 配置檔案複雜性,甚至不知道哪些bean將自動裝配哪個Bean。
在實踐中,我更頃向手動關聯建立,它始終是乾淨,也很好地工作,或者使用 @Autowired 註解,這是更加靈活和建議