Spring 基于构造函数的依赖注入
2023-09-14 09:03:08 时间
当容器调用带有一组参数的类构造函数时,基于构造函数的依赖注入就完成了,其中每个参数代表一个对其他类的依赖。
看个例子:
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/beans
http://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 boot: 一般注入说明(四) Profile配置,Environment环境配置 @Profile注解
- spring属性注入DI
- 18-spring学习-AOP深入操作
- 05-spring-bean注入
- Spring注解开发-属性依赖注入指定名称的bean
- Dubbo和Spring Cloud微服务架构比较
- Spring 基于设值函数的依赖注入
- Spring Bean的生命周期
- 【Spring笔记03】Spring依赖注入各种数据类型
- Spring注入接口还是实现类,同一接口有多个实现类,如何注入
- spring三种注入方式
- 码农小汪-spring框架学习之2-spring IoC and Beans 控制反转 依赖注入 ApplicationContext BeanFactory
- spring为类的静态属性实现注入
- Spring之对象依赖关系(依赖注入Dependency Injection)
- Spring 依赖注入优化
- Spring依赖注入(一):字段注入的方式是如何工作的?
- Spring Cloud Gateway过滤器工厂的使用
- Spring 自动装配之依赖注入 DI运行时序