Bean的自動裝配5

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還是構造器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章