[英]java dependency injection (setter methods injection)
我試圖在學習如何使用Spring之前理解依賴注入。 我的問題是,在下面的基於Setter的依賴注入示例中,為什么沒有TextEditor類的構造函數? 我們這里不需要構造函數嗎? 非常感謝您的幫助!!
(代碼源自: http : //www.tutorialspoint.com/spring/setter_based_dependency_injection.htm )
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker; //Q: Why not a constructor for TextEditor, but only a class variable?
// a setter method to inject the dependency.
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
如果未明確聲明構造函數,則會自動添加默認的無參數公共構造函數。 在教程中 ,
您不必為類提供任何構造函數,但是在執行此操作時必須小心。 編譯器會自動為任何沒有構造函數的類提供無參數的默認構造函數。
Spring容器將使用此構造函數實例化該對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.