Spring由名称(Name)自动装配

在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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值