Spring深入淺出(八),自動裝配,constructor
阿新 • • 發佈:2021-07-12
這種模式與byType非常相似,但它應用於構造器引數。Spring 容器看作 beans,在 XML 配置檔案中 beans 的autowire屬性設定為constructor。然後,它嘗試把它的建構函式的引數與配置檔案中 beans 名稱中的一個進行匹配和連線。如果找到匹配項,它會注入這些 bean,否則,它會丟擲異常。
1. 建立主業務類
package com.clzhang.spring.demo; public class TextEditor { private SpellChecker spellChecker; private String name;public TextEditor(SpellChecker spellChecker, String name) { this.spellChecker = spellChecker; this.name = name; } public SpellChecker getSpellChecker() { return spellChecker; } public String getName() { return name; } public void spellCheck() { spellChecker.checkSpelling(); } }
2. 建立業務邏輯實現類
package com.clzhang.spring.demo; public class SpellChecker { public SpellChecker() { System.out.println("Inside SpellChecker constructor."); } public void checkSpelling() { System.out.println("Inside checkSpelling."); } }
3. 建立主程式
package com.clzhang.spring.demo;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(); } }
4. 配置檔案之前的寫法
<?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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="textEditor" class="com.clzhang.spring.demo.TextEditor"> <constructor-arg ref="spellChecker" /> <constructor-arg value="Generic Text Editor"/> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="com.clzhang.spring.demo.SpellChecker"> </bean> </beans>
5. 配置檔案自動裝配的寫法
<?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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="textEditor" class="com.clzhang.spring.demo.TextEditor" autowire="constructor"> <constructor-arg value="Generic Text Editor"/> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="com.clzhang.spring.demo.SpellChecker"> </bean> </beans>
6. 執行
Inside SpellChecker constructor.
Inside checkSpelling.
本文參考:
https://www.w3cschool.cn/wkspring/jtlb1mmf.html