Spring的依赖注入(一)

本文介绍了依赖注入(DI)的两种主要方式:Setter注入和构造器注入,并提供了XML配置示例及对应的Java类实现,展示了如何利用IoC容器实现对象间的依赖关系。

   对象之间的依赖关系(即一起工作的其它对象(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构造器的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值