依赖注入:spring通过依赖注入来管理Bean之间的依赖关系;
我理解的依赖注入,就是你运行一个类A的时候,需要一些数据,数据可能是基本类型的一个String,也可能是一个自定义的类,比如需要另一个类B,那类B怎么不通过new的显示初始话方式,你就能获得它的实例
一、类依赖其他对象注入的两种方式:
1、初始化时需要类B做入参(构造函数)
例子:
java类:
public class TextEditor {
SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
System.out.println("Inside TextEditor constructor.");
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
public static void main(String[] args) {
new TextEditor(new SpellChecker()).spellCheck();\\手动创建一个类实例给构造函数
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor textEditor = (TextEditor) context.getBean("textEditor");
textEditor.spellCheck();
}
}
说明:如果不用bean管理时,你需要手动用new创建一个实例传递到方法里
配置元数据:
<bean id="textEditor" class="demo.TextEditor">
<constructor-arg ref="spellChecker"/>
bean>
2、成员变量依赖类B赋值(setter设值函数)
例子:
java类:
public class TextEditor {
SpellChecker spellChecker;
public void setSpellChecker(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
public static void main(String[] args) {
new TextEditor().setSpellChecker(new SpellChecker());\\手动创建一个类实例给设值函数
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor textEditor = (TextEditor) context.getBean("textEditor");
textEditor.spellCheck();
}
}
配置元数据:
<bean id="textEditor" class="demo.TextEditor">
<property name="spellChecker" ref="spellChecker"/>
bean>
二、依赖注入的元数据配置的详细说明:
仔细观察XML中文件的配置,发现差异就在bean的属性配置上
1、不同函数的参数传递:构造函数,其他方法函数
| 依赖注入 |
描述 |
| constructor-arg |
构造函数初始化需要参数的时候用到这个
通过ref或value等传递构造函数入参
|
| property |
构造函数外方法的入参传递,使用这个属性 |
2、不同参数类型的值传递
| 属性值类别 |
给哪种类型参数传递值 |
例子 |
| ref |
自定义类的类型;引用具体的类时使用
ref的值为XML配置元数据定义的bean id值
|
|
| value |
String类型的参数 |
|
| list |
列表类型,java.util.List |
INDIA
Pakistan
USA
USA
|
| set |
java.util.Set |
Pakistan
|
| map |
java.util.Map |
|
| props |
java.util.Properties |
INDIA
Pakistan
USA
USA
|