Spring 中有兩種依賴注入的方法冤灾,一種是setter注入,一種是構(gòu)造器注入,多是使用setter注入。
依賴注入:
每個(gè)bean中多多少少都有一些私有變量诅挑,這是與bean一起工作的其他對(duì)象,這些對(duì)象與bean之間的關(guān)系是依賴關(guān)系,什么依賴關(guān)系裹唆,就是bean沒了就這些對(duì)象也就沒了。然而只洒,
每個(gè)bean中的私有變量的實(shí)例化不是由bean來控制的许帐,而且通過Spring容器來控制的,在bean創(chuàng)建的時(shí)候毕谴,由容器注入這些依賴關(guān)系成畦,控制從根本上發(fā)生了反轉(zhuǎn),這也叫做控制反轉(zhuǎn)(IOC)涝开。
構(gòu)造器注入:
每個(gè)構(gòu)造器參數(shù)代表一個(gè)依賴循帐,每個(gè)依賴可以是另一個(gè)bean或者是一個(gè)值。
假如A和B都是一個(gè)bean舀武,現(xiàn)在用構(gòu)造器給A注入B
package x.y;
public class A {
private B b;
private int i;
private String j;
public A(B b, int i, String j) {
this.b = b;
this.i = i;
this.j = j;
}
}
<bean id="B" class="x.y.B"/>
<bean id="A" class="x.y.A">
<!--第一種配置-->
<constructor-arg>
<ref bean="B">
</constructor-arg>
<!--第二種配置-->
<constructor-arg ref="B" />
<constructor-arg index="0" value="1">
<constructor-arg index="1" value="2">
</bean>
可以看到第一個(gè)依賴是一個(gè)bean,第二和第三都是一個(gè)值惧浴,只是簡(jiǎn)單類型不一樣,Spring的<value>true</value>所以spring無法識(shí)別該值的類型奕剃。這時(shí)可以借助索引或者type類型來解決簡(jiǎn)單類型的混淆問題衷旅,index必須從0開始捐腿。如果有兩個(gè)構(gòu)造器參數(shù)都是bean,就不會(huì)有這種混淆的情況
public A(B b, C c) {
this.b=b;
this.c=c;
}
<constructor-arg>
<bean class="x.y.B"/>
</constructor-arg>
<constructor-arg>
<bean class="x.y.C"/>
</constructor-arg>
如果使用setter注入就不會(huì)出現(xiàn)這種情況
setter注入:
package x.y;
public class A {
private B b;
private C c;
private String j;
public A(B b, C c, String j) {
this.b = b;
this.c = c;
this.j = j;
}
}
<bean id="B" class="x.y.B"/>
<bean id="C" class="x.y.C"/>
<bean id="A" class="x.y.A">
<!--bean第一種配置-->
<property name="b" ref="B" />
<!--bean第二種配置-->
<property name="c">
<ref bean="C"/>
</property>
<property name="StringValue" value="1" />
</bean>