2014-10-22 37 views
0

我將如何實例化一個命名構造函數。構造函數是這樣的構造函數在春季參數?

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> 
+3

所以,你要初始化一個bean本身?這沒有任何意義。爲什麼不使用Java配置,這將允許用Java定義bean而不是XML? – 2014-10-22 10:50:09

+0

@JBNizet該類有兩個構造函數。但是我需要這個構造函數在類加​​載不是默認的時候初始化。我可以做到這一點嗎? – 2014-10-22 10:52:07

+0

這是13 GB代碼的一部分。我正在做一些修改。 – 2014-10-22 10:53:20

回答

0

Spring注入依賴關係,以便您不必傳遞僅用作構造函數參數的對象。

定義您需要的任何引用作爲成員,將自動被spring注入,並調用init方法來執行實例化時所需的任何邏輯。

<bean id="machineInPitImpl" class="minestar.pitlink.domain.pitmodel.MachineInPitImpl" abstract="true" 
    init-method="init" 
    p:machineInPitImpl-ref="machineInPitImpl" 
/> 

請注意,我忽略了你正試圖向自己注入一個bean,這並不像通過評論者指出的那樣有意義。

+1

雖然我不認爲這是一項改進。即使使用Spring,使用正確的構造函數也沒有錯。他的代碼不起作用的唯一原因是他將bean注入自身。 – 2014-10-22 11:59:45

0

您試圖注入在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."); 
     } 

讓你嘗試這樣做的sense.when,

ApplicationContext context = 
      new ClassPathXmlApplicationContext("app.xml"); 

     TextEditor te = (TextEditor) context.getBean("textEditor");