試試這個:
<bean id="objImpl" class="com.work.Obj" autowire="constructor">
<constructor-arg index="0" ref="interfaceImpl"/>
</bean>
在這裏,你已經指定了com.work.Obj
類型的bean應當使用創建的自動裝配構造。如果您指定了任何構造函數arg,那麼它將覆蓋自動裝配參數。所以索引0是明確提供的。其他未明確提供的參數將按類型自動佈線。
注意:構造自動裝配有相同的限制,byType
- 春天不會試圖去猜測當它找到匹配的構造精氨酸,多種bean自動裝配哪個Bean。此外,如果類有多個構造函數,其中任何一個都可以通過自動裝配來滿足,那麼Spring將不會嘗試猜測使用哪個構造函數。在這種情況下你會得到一個例外。
編輯:對於這項工作,類型Interface
(構造ARG型)的其它豆類除了一個需要被自動連接,應註明autowire-candidate=false
實施例:
<bean id="impl1" class="stackoverflow.SomeImpl" autowire-candidate="false"/>
<bean id="impl2" class="stackoverflow.SomeImpl"/>
<bean id="obj" class="stackoverflow.Obj" autowire="constructor">
<constructor-arg index="0" ref="impl1"/>
</bean>
和Obj類:
package stackoverflow;
public class Obj {
public Obj(SomeInterface i1, SomeInterface i2){
System.out.println("i1" + i1);
System.out.println("i2" + i2);
}
}
這裏SomeImpl implements SomeInterface
。運行時impl2
bean在第二個構造函數arg i2
中自動裝配。第一個參數是在Spring配置中手動提供的。
來源
2014-07-24 11:31:55
Pat
什麼阻止你使用ref? – hutingung
爲什麼不自動連接另一個呢? –
我不想在這個問題中想到這個問題,因爲它太長了。所以我只是說,因爲遺留項目代碼,因爲糟糕的設計,噓噓bla ... – Simeon