Bean的自动装配----Autodetect
Autodetect模式
通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。
案例:
AddressServiceImpl.java
public class AddressServiceImpl {
private String address;
public void setAddress(String address) {
this.address = address;
}
}
EmpServiceImpl.java
public class EmpServiceImpl {
private AddressServiceImpl companyAddress;
public EmpServiceImpl(AddressServiceImpl companyAddress) {
super();
this.companyAddress = companyAddress;
}
public EmpServiceImpl() {
super();
}
public void setCompanyAddress(AddressServiceImpl companyAddress) {
this.companyAddress = companyAddress;
}
}
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;
}
}
<?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>
-->
<!-- 采用autodetect -->
<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton" autowire="autodetect"/>
</beans>
总结一句话:byType byName采用ioc中的set方法进行依赖注入的;若采用构造器则采用构造器的方式进行注入;Autodetect根据bean中是否有 无参数的构造器来选择bean的注入方式是采用byType还是构造器