在Spring框架,可以用 auto-wiring 功能會自動裝配Bean。要啟用它,只需要在 <bean>定義“autowire”屬性。
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" />
在Spring中,支持 5 自動裝配模式。
no – 缺省情況下,自動配置是通過“ref”屬性手動設(shè)定
byName – 根據(jù)屬性名稱自動裝配。如果一個(gè)bean的名稱和其他bean屬性的名稱是一樣的,將會自裝配它。
byType – 按數(shù)據(jù)類型自動裝配。如果一個(gè)bean的數(shù)據(jù)類型是用其它bean屬性的數(shù)據(jù)類型,兼容并自動裝配它。
constructor – 在構(gòu)造函數(shù)參數(shù)的byType方式。
autodetect – 如果找到默認(rèn)的構(gòu)造函數(shù),使用“自動裝配用構(gòu)造”; 否則,使用“按類型自動裝配”。
示例
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 { //...}
- Auto-Wiring ‘no’
這是默認(rèn)的模式,你需要通過 'ref' 屬性來連接 bean。
<bean id="customer" class="com.yiibai.common.Customer"> <property name="person" ref="person" /> </bean> <bean id="person" class="com.yiibai.common.Person" /> - 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按名稱自動裝配 - Auto-Wiring ‘byType’
通過按屬性的數(shù)據(jù)類型自動裝配Bean。在這種情況下,由于“Person” bean中的數(shù)據(jù)類型是與“customer” bean的屬性(Person對象)的數(shù)據(jù)類型一樣的,所以,Spring會自動通過setter方法將其自動裝配。– “setPerson(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="byType" /><bean id="person" class="com.yiibai.common.Person" />
查看完整的示例 – Spring通過類型自動裝配 - Auto-Wiring ‘constructor’
通過構(gòu)造函數(shù)參數(shù)的數(shù)據(jù)類型按屬性自動裝配Bean。在這種情況下,由于“person” bean的數(shù)據(jù)類型與“customer” bean的屬性(Person對象)的構(gòu)造函數(shù)參數(shù)的數(shù)據(jù)類型是一樣的,所以,Spring通過構(gòu)造方法自動裝配 – “public Customer(Person person)“.
<bean id="customer" class="com.yiibai.common.Customer" autowire="constructor" /> <bean id="person" class="com.yiibai.common.Person" />