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>

运行结果:

原文地址:https://www.cnblogs.com/fangpengchengbupter/p/7816012.html