Spring2.5.6 中Bean的自动装配六种模式其一
Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系。因此,如果可能的话,可以自动让Spring通过检查BeanFactory中的内容,来替我们指定bean的协作者(其他被依赖的bean)。autowire一共有六种类型。由于autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥![2] 在xml配置文件中,可以在<bean/>元素中使用autowire属性指定:
|
模式 |
说明 |
|
Default |
在每个bean中都一个autowire=default的默认配置它的含义是: 采用beans和跟标签中的default-autowire="属性值"一样的设置。
|
|
On |
不使用自动装配,必须通过ref元素指定依赖,默认设置。
|
下来我们就用案例来证明一下:准备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;
}
}
default和no值default.xml配置文件
<?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" default-autowire="no"> <bean id="homeAddressServiceImpl" class="cn.csdn.service.HomeAddressServiceImpl" scope="singleton"> <property name="address"> <value>北京海淀上地软件园</value> </property> </bean> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton" autowire="default" /> </beans>
测试类:(junit测试)
public class App {
@Test
public void test(){
ApplicationContext ac= new ClassPathXmlApplicationContext("classpath:default.xml"); EmpServiceImpl emp = (EmpServiceImpl) ac.getBean("empServiceImpl");
}
}
声明:
<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"
scope="singleton" autowire="no" />
不使用自动装配,必须通过ref元素指定依赖,默认设置。
结束语:这几期将陆续的为大家解析Bean的自动装配中autowire中的值!
<!--EndFragment-->
本文介绍了Spring框架中Bean的自动装配机制及其六种模式之一的默认模式。通过实例演示了如何在XML配置文件中使用autowire属性指定自动装配,并解释了default和no模式的区别。
203

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



