- 相关概念
依赖:A组件调用B组件的方法,称A组件依赖B组件。
依赖注入(Dependency Injection,DI):也叫控制反转(Inversion of Control,IoC)。当某个Java实例(调用者)需要另一个Java实例(被调用者)时,通常由调用者来创建被调用者的实例,在依赖注入模式下,创建调用者的工作不再由调用者完成,而是依赖外部容器的注入。
- 实现方式
设值注入:IoC容器使用属性的setter方法来注入被依赖的实例。
构造注入:IoC容器使用构造器来注入被依赖的实例。
- 设值注入
为了便于接下来的理解,涉及到的java对象依赖关系表示如下:
在需要实例化某个类的调用类中写入setter方法:
private Axe axe;
//设值注入所需的setter方法
public void setAxe(Axe axe){
this.axe = axe;
}
//调用axe的方法或访问属性
your code here...
使用XML配置文件来指定实例间的依赖关系:
<?xml version="1.0" encoding="GBK"?>
<!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置chinese实例,其实现类是lee.Chinese -->
<bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
<!-- 将stoneAxe注入给axe属性 -->
<property name="axe" ref="stoneAxe"/>
</bean>
<!-- 配置stoneAxe实例,其实现类是StoneAxe -->
<bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/>
</beans>
该配置文件中,Spring配置Bean实例通常会指定两个属性:
id:指定该Bean的唯一标识,程序通过id属性值来访问该Bean实例。
class:指定该Bean的实现类。Spring容器会使用XML解析器读取该属性值,并利用反射来创建该实现类的和实例。
TIPs:可以在Spring的projects目录的org.springframework.beans、org.springframework.content等子目录的\src\main\resources路径下找到各种*.xsd文件,这些都是Spring配置文件的XML Schema文件。
- 构造注入
private Axe axe;
//默认的构造器
public Chinese()
{
}
//构造注入所需的带参数的构造器
public Chinese(Axe axe)
{
this.axe = axe;
}
<?xml version="1.0" encoding="GBK"?>
<!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置chinese实例,其实现类是Chinese -->
<bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
<!-- 使用构造注入,为chinese实例注入steelAxe实例 -->
<constructor-arg ref="steelAxe"/>
</bean>
<!-- 配置stoneAxe实例,其实现类是StoneAxe -->
<bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/>
<!-- 配置steelAxe实例,其实现类是SteelAxe -->
<bean id="stoneAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
</beans>
配置文件中使用<constructor-arg.../>指定构造器的参数,也就是注入的实例。可以指定一个index属性,用于指定该构造函数参数值将作为第几个构造参数值。
- 两种注入方式的选择
- 使用Spring IoC容器的3个基本要点
- 面向接口编程。将各组件的耦合提升到接口层次,易于后期的扩展。
- 各组件由Spring负责初始化。
- 采用XML配置文件或者Annotation来管理Bean的实例化、依赖关系。