您的位置:首页 > 编程语言 > Java开发

Spring由名称(Name)自动装配

2018-03-01 14:37 211 查看
在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]]
看看下面另一个例子,这一次,装配将会失败,导致bean “addressABC”不匹配“customer” bean的属性名称。
<?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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: