Spring的两种注入方式

带着前面的疑问,不断的学习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,构造注入更加有用处

·依赖关系只能在构造器中设定,则只有组建的创建者才能改变组建的依赖关系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值