當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 基于构造函数的依赖注入
生活随笔
收集整理的這篇文章主要介紹了
Spring 基于构造函数的依赖注入
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
當(dāng)容器調(diào)用帶有一組參數(shù)的類構(gòu)造函數(shù)時,基于構(gòu)造函數(shù)的依賴注入就完成了,其中每個參數(shù)代表一個對其他類的依賴。
看個例子:
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的構(gòu)造函數(shù)里有一個參數(shù),代表對SpellChecker的依賴。
SpellChecker的源代碼:
public class SpellChecker {public SpellChecker(){System.out.println("Inside SpellChecker constructor." );}public void checkSpelling() {System.out.println("Inside checkSpelling." );} }MainApp.java的內(nèi)容:
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的內(nèi)容:
<?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>通過構(gòu)造函數(shù)注入依賴的核心是這個標(biāo)簽:
單步調(diào)試觀察:創(chuàng)建Spring IOC容器:
創(chuàng)建TextEditor bean實例:
檢測到構(gòu)造函數(shù)里有一個參數(shù)依賴:
依賴于另一個bean:spellChecker
因此SpellChecker實例也被創(chuàng)建出來了:
輸出:
Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling.如果你想要向一個對象傳遞一個引用,你需要使用 標(biāo)簽的 ref 屬性,如果你想要直接傳遞值,那么你應(yīng)該使用如上所示的 value 屬性。
要獲取更多Jerry的原創(chuàng)文章,請關(guān)注公眾號"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Spring 基于构造函数的依赖注入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据二叉树的中序序列+前序序列 可以唯一
- 下一篇: gradle idea java ssm