當容器調用帶有一組參數的類構造函數時,基於構造函數的DI就完成了,其中每一個參數表明一個對其餘類的依賴。java
TextEditor.java文件的內容:ide
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文件的內容this
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的內容,它有基於構造函數注入的配置:spa
<bean id="textEditor" class="com.tuorialsponit.TextEditor"> <constructor-arg ref="spellChecker"></constructor-arg> </bean> <bean id="spellChecker" class="com.tuorialsponit.SpellChecker"> </bean>
運行結果:code