以前写的是根据setter设值注入,还有一种为bean注入值的方法经过构造器注入。仍是经过“人”和“斧子”之间的关系举例;java
Chinese类注入方式构造器注入;spring
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=“”>:ide
<?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”表示为该构造器中的第一个参数。this
Spring会采起以下反射来注入stoneAxe:code
//获取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实列建立完成后就已经完成了依赖注入关系。xml
注意:交由给Spring管理的Bean,没有使用构造注入时,必定要含有无参构造方法。不然该Bean没法被实列化。对象