设值注入:
先经过
无参数的构造函数建立一个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>
比较:
建议使用 设值注入;
对于依赖关系无需变化的注入,尽可能采用构造注入;而其余依赖关系的注入,则优先考虑设值注入;