在Spring中,“按名称自动装配”是指,如果一个bean的名称与其他bean属性的名称是一样的,那么将自动装配它。
例如,如果“customer” bean公开一个“address”属性,Spring会找到“address” bean在当前容器中,并自动装配。如果没有匹配找到,那么什么也不做。
1. Beans
这里有两个 beans, 分别是:customer 和 address.
public class Customer {
private Address address;
@Override
public String toString() {
return "Customer [address=" + address + "]";
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
public class Address {
private String fulladdress;
public String getFulladdress() {
return fulladdress;
}
public void setFulladdress(String fulladdress) {
this.fulladdress = fulladdress;
}
@Override
public String toString() {
return "Address [fulladdress=" + fulladdress + "]";
}
}
2. Spring 装配
通常情况下,您明确装配Bean,这样通过 ref 属性:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.ray.common.Customer">
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.ray.common.Address">
<property name="fulladdress" value="Zhuhai" />
</bean>
</beans>
输出
Customer [address=Address [fulladdress=Zhuhai]]
使用按名称启用自动装配,你不必再声明属性标记。只要在“address” bean是相同于“customer” bean 的“address”属性名称,Spring会自动装配它。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.ray.common.Customer" autowire="byName"/>
<bean id="address" class="com.ray.common.Address">
<property name="fulladdress" value="Zhuhai" />
</bean>
</beans>
输出
Customer [address=Address [fulladdress=Zhuhai]]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.ray.common.Customer" autowire="byName"/>
<bean id="addressABC" class="com.ray.common.Address">
<property name="fulladdress" value="Zhuhai" />
</bean>
</beans>
输出
Customer [address=null]