設值注入:
先經過
無參數的構造函數建立一個Bean實例,而後調用對應的setter方法注入依賴關係;
配置文件:
-
<?xml version="1.0" encoding="GBK"?><!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd語義約束 --><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <property name="axe" ref="steelAxe"/> <property name="Stuname" value="zhangsan"/>
</bean> <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/></beans>
構造注入:
直接調用
有參數的構造器,當bean實例建立完成後,已經完成了依賴關係的注入;
配置文件
-
<?xml version="1.0" encoding="GBK"?><!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd語義約束 --><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <constructor-arg ref="steelAxe" type="org.crazyit.app.service.Axe"/> <constructor-arg value="zhangsan" type="String"/>
</bean> <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/></beans>
比較:
建議使用 設值注入;
對於依賴關係無需變化的注入,儘可能採用構造注入;而其餘依賴關係的注入,則優先考慮設值注入;