Spring-基於構造函數的依賴注入


Spring基於構造函數的依賴注入

當容器調用帶有一組參數的類構造函數時,基於構造函數的DI就完成了,其中每個參數代表一個對其他類的依賴。

TextEditor.java文件的內容:

package com.tuorialsponit;

public class TextEditor {
    private SpellChecker spellChecker;
    public TextEditor(SpellChecker spellChecker){
        this.spellChecker = spellChecker;
    }
    
    public void spellCheck() {
        spellChecker.checkSpelling();
    }
}

下面是另一個依賴類文件SpellChecker.java內容

package com.tuorialsponit;

public class SpellChecker {
    public SpellChecker(){
        System.out.println("Inside SpellChecker constructor.");
    }
    
    public void checkSpelling(){
        System.out.println("Inside checkSpelling.");
    }
}

以下是MainApp.java文件的內容

public class MainApp {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//    
        TextEditor textEditor = (TextEditor) context.getBean("textEditor");
        textEditor.spellCheck();
    }
}

下面是配置文件Beans.xml的內容,它有基於構造函數注入的配置:

<bean id="textEditor" class="com.tuorialsponit.TextEditor">
         <constructor-arg ref="spellChecker"></constructor-arg>
     </bean>
     
     <bean id="spellChecker" class="com.tuorialsponit.SpellChecker">
     </bean>

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM