以前寫的是根據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沒法被實列化。對象