Spring深入浅出(八),自动装配,constructor
这种模式与 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