日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring 基于构造函数的依赖注入

發(fā)布時間:2023/12/19 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。