Spring 中Bean的自动装配六种模式其四
Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系。因此,如果可能的话,可以自动让Spring通过检查BeanFactory中的内容,来替我们指定bean的协作者(其他被依赖的bean)。autowire一共有六种类型。由于autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥![2] 在xml配置文件中,可以在<bean/>元素中使用autowire属性指定:
|
模式 |
说明 |
|
Constructor |
与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。 |
下来我们就用案例来证明一下:准备3个类:
public class AddressServiceImpl {
/**住址*/
private String address;
public void setAddress(String address){
this.address=address;
}
}
public class HomeAddressServiceImpl extends AddressServiceImpl {
private String address;
public void setAddress(String address){
this.address=address;
}
public HomeAddressServiceImpl() {
super();
}
public HomeAddressServiceImpl(String address){
this.address=address;
}
}
public class EmpServiceImpl {
/**公司地址*/
private AddressServiceImpl companyAddress;
public void setCompanyAddress(AddressServiceImpl companyAddress){
this.companyAddress=companyAddress;
}
}
Constructor值的constructor.xml配置文件
Constructor:与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的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-2.0.xsd">
<!-- 配置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>
测试类:(junit测试)
public class App {
@Test
public void test(){
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:byName.xml"); EmpServiceImpl emp = (EmpServiceImpl) ac.getBean("empServiceImpl");
}
}
本文详细介绍了Spring框架中Bean的自动装配机制,并通过具体案例解释了构造器方式的自动装配方法。构造器自动装配与byType类似,但在构造器参数上应用。若未找到匹配类型,则会引发异常。
2236

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



