當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 基于构造函数的依赖注入
生活随笔
收集整理的這篇文章主要介紹了
Spring 基于构造函数的依赖注入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當容器調用帶有一組參數的類構造函數時,基于構造函數的依賴注入就完成了,其中每個參數代表一個對其他類的依賴。
看個例子:
TextEditor的源代碼:
public class TextEditor {private SpellChecker spellChecker;public TextEditor(SpellChecker spellChecker) {System.out.println("Inside TextEditor constructor." );this.spellChecker = spellChecker;}public void spellCheck() {spellChecker.checkSpelling();}}TextEditor的構造函數里有一個參數,代表對SpellChecker的依賴。
SpellChecker的源代碼:
public class SpellChecker {public SpellChecker(){System.out.println("Inside SpellChecker constructor." );}public void checkSpelling() {System.out.println("Inside checkSpelling." );} }MainApp.java的內容:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");TextEditor te = (TextEditor) context.getBean("textEditor");te.spellCheck();} }Beans.xml的內容:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><!-- Definition for textEditor bean --><bean id="textEditor" class="com.sap.TextEditor"><constructor-arg ref="spellChecker"/></bean><!-- Definition for spellChecker bean --><bean id="spellChecker" class="com.sap.SpellChecker"></bean></beans>通過構造函數注入依賴的核心是這個標簽:
單步調試觀察:創建Spring IOC容器:
創建TextEditor bean實例:
檢測到構造函數里有一個參數依賴:
依賴于另一個bean:spellChecker
因此SpellChecker實例也被創建出來了:
輸出:
Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling.如果你想要向一個對象傳遞一個引用,你需要使用 標簽的 ref 屬性,如果你想要直接傳遞值,那么你應該使用如上所示的 value 屬性。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Spring 基于构造函数的依赖注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据二叉树的中序序列+前序序列 可以唯一
- 下一篇: Spring 基于设值函数的依赖注入