Spring由名称(Name)自动装配
在Spring中,“按名称自动装配”是指,如果一个bean的名称与其他bean属性的名称是一样的,那么将自动装配它。 例如,如果“customer” bean公开一个“address”属性,Spring会找到“address” bean在当前容器中,并自动装配。如果没有匹配找到,那么什么也不做。 你可以通过 autowire="byName" 自动装配像下面这样: <!-- customer has a property name "address" --> <bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="address" class="com.yiibai.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.yiibai.common.Customer" autowire="byName" /> <bean id="addressABC" class="com.yiibai.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean> 输出 Customer [address=null]
<!-- customer has a property name "address" --> <bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="address" class="com.yiibai.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
1. Beans
这里有两个 beans, 分别是:customer 和 address.
package com.yiibai.common;
public class Customer
{
private Address address;
//...
}
package com.yiibai.common;
public class Address
{
private String fulladdress;
//...
}
2. Spring 装配
<bean id="customer" class="com.yiibai.common.Customer" > <property name="address" ref="address" /> </bean> <bean id="address" class="com.yiibai.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
输出
Customer [address=Address [fulladdress=YiLong Road, CA 188]]
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="address" class="com.yiibai.common.Address" > <property name="fulladdress" value="YiLong Road, CA 188" /> </bean>
输出
Customer [address=Address [fulladdress=YiLong Road, CA 188]]
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" /> <bean id="addressABC" class="com.yiibai.common.Address" > <property name="fulladdress" value="Block A 888, CA" /> </bean>
输出
Customer [address=null]
交流与评论