构造注入

    之前写的是根据setter设值注入,还有一种为bean注入值的方法通过构造器注入。还是通过“人”和“斧子”之间的关系举例;

    Chinese类注入方式构造器注入;

package com.custle.spring;

public class Chinese implements Person {

	private Axe axe;
	
	//构造器注入所需要的斧子
	public Chinese(Axe axe) {
		this.axe = axe;
	}
	
	@Override
	public void useAxe() {
		System.out.println(axe.chop());
	}

}

    将配置文件<bean>中的property修改为<constructor-arg ref=“”>:

<?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">
	<!-- 将 stoneAxe注入chinese中的axe属性-->
    <bean id="chinese" class="com.custle.spring.Chinese">  
        <!-- 通过构造器注入 -->
        <constructor-arg index="0" ref="stoneAxe"/>
    </bean>  
    
    <!-- 将StoneAxe交给Srping管理 -->
    <bean id="stoneAxe" class="com.custle.spring.StoneAxe"/>  
</beans>

    其中index用于指定构造器参数位置,“0”表示为该构造器中的第一个参数。

    Spring会采取如下反射来注入stoneAxe:

//获取Chinese的Class对象
Class chinese = Class.forName("com.custle.spring.Chinese");
//获取构造器的参数
Constructor constructor = chinese.getConstructor(StoneAxe.class);
//以指定构造器创建Bean实列
Object bean = constructor.newInstance(StoneAxe.class);

    构造注入和设置注入区别在于:创建Chinese时,注入"斧子"axe的时间不同,设值注入先通过Chinese的无参构造器创建一个Bean实列,然后通过propery为setAxe()注入,而构造注入是当该Bean实列创建完成后就已经完成了依赖注入关系。

    注意:交由给Spring管理的Bean,没有使用构造注入时,一定要含有无参构造方法。否则该Bean无法被实列化。

转载于:https://my.oschina.net/u/3697923/blog/1616731

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值