[英]Constructor args in Spring?
我將如何實例化一個命名構造函數。 構造函數是這樣的
public MachineInPitImpl(MachineInPitImpl mip){
//here are the attributes initialised
}
在春季,我將如何將此構造函數作為Constructor-args給出。
我已經嘗試過了,但是不起作用,它仍然初始化默認構造函數。 我不想初始化默認的缺點。 我希望彈簧初始化上述構造函數
<bean id="machineInPitImpl" class="minestar.pitlink.domain.pitmodel.MachineInPitImpl" abstract="true">
<constructor-arg ref="machineInPitImpl"/>
</bean>
Spring注入依賴項,這樣您就不必只傳遞對象作為構造函數參數。
將所需的任何引用定義為將由spring自動注入的成員,並調用init方法以在實例化時執行所需的邏輯。
<bean id="machineInPitImpl" class="minestar.pitlink.domain.pitmodel.MachineInPitImpl" abstract="true"
init-method="init"
p:machineInPitImpl-ref="machineInPitImpl"
/>
請注意,我忽略了您正在嘗試將一個bean注入自身,這沒有評論者所指出的意義。
您嘗試在xml中注入相同的bean引用,
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg ref="spellChecker"/>
</bean>
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
public TextEditor(SpellChecker spellChecker) {
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
很有道理。當您嘗試這樣做時,
ApplicationContext context =
new ClassPathXmlApplicationContext("app.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.