Spring 中Bean的自动装配六种模式其五
Spring IoC容器可以自动装配(autowire)相互协作bean之间的关联关系。因此,如果可能的话,可以自动让Spring通过检查BeanFactory中的内容,来替我们指定bean的协作者(其他被依赖的bean)。autowire一共有六种类型。由于autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥![2] 在xml配置文件中,可以在<bean/>元素中使用autowire属性指定:
模式 |
说明 |
Antodetect |
通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。
|
下来我们就用案例来证明一下:准备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;
}
}
Antodetect值的antodetect.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"> <!-- 配置bean --> <bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl" scope="singleton"> <property name="address"> <value>北京</value> </property> </bean> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton" autowire="autodetect"/> </beans>
测试类:(junit测试)
public class App {
@Test
public void test(){
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:byName.xml"); EmpServiceImpl emp = (EmpServiceImpl) ac.getBean("empServiceImpl");
}
}
结束语:这几期都是为大家提供自动装配Bean的属性值,为学习Spring打下了良好的基础还只的遗体的就是,*可以设置bean使自动装配失效:
采用xml格式配置bean时,将<bean/>元素的autowire-candidate属性设置为false,这样容器在查找自动装配对象时,将不考虑该bean,即它不会被考虑作为其它bean自动装配的候选者,但是该bean本身还是可以使用自动装配来注入其它bean的。
<!--EndFragment-->