在Spring中,“按名稱自動裝配”是指,如果一個bean的名稱與其他bean屬性的名稱是一樣的,那麼將自動裝配它。
例如,如果“customer” bean公開一個“address”屬性,Spring會找到“address” bean在當前容器中,並自動裝配。如果沒有匹配找到,那麼什麼也不做。
你可以通過 autowire="byName" 自動裝配像下麵這樣:
<!-- customer has a property name "address" --> <bean id="customer" class="com.xuhuhu.common.Customer" autowire="byName" /> <bean id="address" class="com.xuhuhu.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
看看Spring自動裝配的完整例子。
1. Beans
這裏有兩個 beans, 分別是:customer 和 address.
package com.xuhuhu.common; public class Customer { private Address address; //... }
package com.xuhuhu.common; public class Address { private String fulladdress; //... }
2. Spring 裝配
通常情況下,您明確裝配Bean,這樣通過 ref 屬性:
<bean id="customer" class="com.xuhuhu.common.Customer" > <property name="address" ref="address" /> </bean> <bean id="address" class="com.xuhuhu.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
輸出
Customer [address=Address [fulladdress=YiLong Road, CA 188]]
使用按名稱啟用自動裝配,你不必再聲明屬性標記。只要在“address” bean是相同於“customer” bean 的“address”屬性名稱,Spring會自動裝配它。
<bean id="customer" class="com.xuhuhu.common.Customer" autowire="byName" /> <bean id="address" class="com.xuhuhu.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
輸出
Customer [address=Address [fulladdress=YiLong Road, CA 188]]
看看下麵另一個例子,這一次,裝配將會失敗,導致bean “addressABC”不匹配“customer” bean的屬性名稱。
<bean id="customer" class="com.xuhuhu.common.Customer" autowire="byName" /> <bean id="addressABC" class="com.xuhuhu.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
輸出
Customer [address=null]
上一篇:
Spring由類型(Type)自動裝配
下一篇:
Spring由構造方法自動裝配