带着前面的疑问,不断的学习Spring的知识,然后再回过头去解决那些疑问。
现在我们来看看Spring的两种注入方式:
· 设值注入
设值注入式利用setter的方式为Bean注入依赖关系的方式。
上一节就是使用设值注入为Bean注入依赖关系。
设值注入的关键就是在类中必须存在一个该属性的setter方法,否则是无法实现的。
· 构造注入
构造注入是利用构造器来设置依赖关系的方式。
来看范例:
public class Chinese implements Person{
//斧头
private Aex aex;
private Aex aex1;
public Aex getAex() {
return aex;
}
public void setAex(Aex aex) {
this.aex = aex;
}
/**
* 默认构造函数
*/
public Chinese(){
}
/**
* 构造器注入
*/
public Chinese(Aex aex,Aex aex1){
this.aex=aex;
this.aex1=aex1;
}
/**
* 使用斧头
*/
public void useAex(String name){
System.out.println(name+aex.chop());
System.out.println(name+aex1.chop());
}
}
Bean配置:
<beans>
<!-- 配置chinese实例,其实现类是org.spring.demo1.Chinese -->
<bean id="chinese" class="org.spring.demo1.Chinese">
<constructor-arg ref="stoneAex"></constructor-arg>
<constructor-arg ref="steelAex"></constructor-arg>
</bean>
<!-- 配置stoneAxe实例,其实现类是org.spring.demo1.StoneAxe -->
<bean id="stoneAex" class="org.spring.demo1.StoneAex">
</bean>
<!-- 配置steelAxe实例,其实现类是org.spring.demo1.SteelAxe -->
<bean id="steelAex" class="org.spring.demo1.SteelAex">
</bean>
</beans>
使用构造器注入,要注意顺序,构造器注入的顺序对应构造函数中参数的顺序。
设值注入较之构造注入的优势:
·采用设置注入,容易让程序员理解,依赖关系更加直观、自然
·多参数的构造器会导致构造器过于臃肿,很难阅读。同时Spring在创建Bean实例的时候,要同时实例化构造器重其依赖的全部实例,这点导致了性能下降。
构造注入的优势:
·需要按照一定的顺序决定依赖注入的顺序
·依赖关系无须变化的Bean,构造注入更加有用处
·依赖关系只能在构造器中设定,则只有组建的创建者才能改变组建的依赖关系。