1.依赖注入
(1) 依赖注入(DI)的概念:某个bean的依赖项,由容器来负责注入维护,而非我们自己手动去维护,以此来达到bean之间解耦的目的,如下
//情况一:不使用依赖注入
public class A {}
public class B {
//B依赖了A对象,这种依赖关系是由我们自己手动来维护的,编码于代码之中,是强依赖
private A a = new A();
}
//情况二:使用依赖注入
@Component
public class A {}
@Component
public class B {
//B依赖了A对象,这个A对象是由容器来提供的,无需我们关心
@Autowired
private A a;
}
(2) 依赖注入的两种方式
- 基于构造函数的依赖注入:容器通过调用带有参数的构造函数来完成依赖项的注入,其中构造函数中的每个参数都代表一个依赖项,其参数解析规则如下
//例一:
//ExampleA继承自ExampleB
public class ExampleA extends ExampleB {}
public class ExampleB {}
public class Combine {
//Combine依赖了ExampleA和ExampleB
public Combine(ExampleA a, ExampleB b) {
}
}
<!-- xml配置文件 -->
<beans ...>
<bean id="exampleA" class="cn.example.spring.boke.ExampleA"></bean>
<bean id="exampleB" class="cn.example.spring.boke.ExampleB"></bean>
<bean id="combine" class="cn.example.spring.boke.Combine">
<!-- Spring会按照类型进行精确匹配,因此1会被注入到构造函数的第二个参数b中,而2会被注入到构造函数的第一个参数a中,此时与这些构造函数标签声明的先后顺序无关 -->
<constructor-arg ref="exampleB"></constructor-arg> <!-- 1 -->
<constructor-arg ref="exampleA"></constructor-arg> <!-- 2 -->
</bean>
</beans>
//例二:
//将Combine构造函数变更一下
public class Combine {
//构造函数参数均为ExampleB
public Combine(ExampleB b1, ExampleB b2) {
}
}
<!-- xml配置文件 -->
<bean id="combine" class="cn.example.spring.boke.Combine">
<!-- 此时无法进行精确匹配,因为构造函数参数均为ExampleB,这时就会按照这些构造函数标签声明的先后顺序进行依赖项的注入,
结果为1会被注入到构造函数的第一个参数b1中,而2会被注入到构造函数的第二个参数b2中,如果将这两个构造函数标签的声明顺序颠倒一下,结果也会随之相反 -->
<constructor-arg ref="exampleB"></constructor-arg> <!-- 1 -->
<constructor-arg ref="exampleA"></constructor-arg> <!-- 2 -->
</bean>
//例三
public class ExampleC {
public ExampleC(int number, String str) {
}
}
<!-- xml配置文件1 -->
<beans ...>
<bean id="c" class="cn.example.spring.boke.ExampleC">
<!-- 此时的Spring无法判断2000或50000究竟是一个int还是一个String,因此它首先会采取例二中的办法,按构造函数标签的声明顺序进行注入,结果为number被注入2000,str被注入字符串50000 -->
<constructor-arg value="2000"></constructor-arg>
<constructor-arg value="50000"></constructor-arg>
</bean>
</beans>
<!-- xml配置文件2 -->
<beans ...>
<bean id="c" class="cn.example.spring.boke.ExampleC">
<!-- 可以使用type属性,指定希望注入的参数的类型,来解决歧义问题,结果number被注入50000,str被注入字符串2000,但是如果构造函数参数列表中有多个类型相同的参数,则又会按照构造函数标签的声明顺序进行注入 -->
<constructor-arg type="java.lang.String" value="2000"></constructor-arg>
<constructor-arg type="int" value="50000"></constructor-arg>
</bean>
</beans>
<!-- xml配置文件3 -->
<bean id="c" class="cn.example.spring.boke.ExampleC">
<!-- 使用index属性,按构造函数参数索引位置进行注入,index属性为0的构造函数标签的值会被注入到构造函数的第一个参数,以此类推 -->
<constructor-arg index="1" value="50000"></constructor-arg>
<constructor-arg index="0" value="2000">