对象之间的依赖关系(即一起工作的其它对象(bean))只会通过以下几种方式来实现:a 通过构造器的参数;b 通过工厂方法的参数;c 构造函数或者工厂方法创建的对象设置属性;
IoC容器的工作就是创建Bean时注入那些依赖关系 .想对于由bean 自己来控制其实例化,直接在构造器中指定依赖关系或者类似服务定位器模式这3种自主控制依赖关系注入的方法来说 ,控制从根本上发生了倒转,这也正是反转控制(Inversion of Control,IOC)名字的由来.
使用DI原则后,代码将更加清晰.而Bean再也不用管对象之间 的依赖关系,因此可以实现更高层次的松耦合,DI主要有两种注入方式,即Setter注入以及构造器注入
下面将给个DI的两种注入方式的例子:
首先是一个用XML格式定义的Setter DI例子。相关的XML配置如下:
<bean id="exampleBean" class="examples.ExampleBean">
<!-- setter injection using the nested <ref/> element -->
<property name="beanOne"><ref bean="anotherExampleBean"/></property>
<!-- setter injection using the neater 'ref' attribute -->
<property name="beanTwo" ref="yetAnotherBean"/>
<property name="integerProperty" value="1"/>
</bean>
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } }可以看到bean类中的setter方法与xml文件中配置的属性是一一对应的.接着是构造器注入的例子<bean id="exampleBean" class="examples.ExampleBean"> <!-- constructor injection using the nested<ref/>element --> <constructor-arg> <ref bean="anotherExampleBean"/> </constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref="yetAnotherBean"/> <constructor-arg type="int" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean( AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; } }可以发现,在xml bean定义中指定的构造器参数将被用来作为传递给类ExampleBean构造器的参数。
本文介绍了依赖注入(DI)的两种主要方式:Setter注入和构造器注入,并提供了XML配置示例及对应的Java类实现,展示了如何利用IoC容器实现对象间的依赖关系。

被折叠的 条评论
为什么被折叠?



