Bean的自动装配---Constructor
Constructor模式
与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。
案例:
AddressServiceImpl.java
public class AddressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
HomeAdsressServiceImpl.java
public class HomeAdsressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
public HomeAdsressServiceImpl() {
super();
}
public HomeAdsressServiceImpl(String address) {
super();
this.address = address;
}
}
EmpServiceImpl.java
public class EmpServiceImpl {
private AddressServiceImpl companyAddress;
public EmpServiceImpl(AddressServiceImpl companyAddress) {
super();
this.companyAddress = companyAddress;
}
}
<?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-2.5.xsd">
<bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl"
scope="singleton">
<property name="address">
<value>北京</value>
</property>
</bean>
<!-- 配置bean 相同类型只能在 配置文件中出现一次
<bean id="homeAddressServiceImpl" class="cn.csdn.service.HomeAddressServiceImpl" scope="prototype">
<property name="address">
<value>北京</value>
</property>
</bean>
-->
<!-- 自动装配 采用constructor 构造器中的参数是按照byType进行装配的 -->
<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton" autowire="constructor"/>
</beans>
Bean自动装配详解
805

被折叠的 条评论
为什么被折叠?



