当容器调用带有一组参数的类构造函数时,基于构造函数的依赖注入就完成了,其中每个参数代表一个对其他类的依赖。
看个例子:
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 属性。