SPRING.NET 1.3.2 学习5--依赖注入

1.使用属性依赖注入:

XML

<object id="exampleObject" type="Examples.ExampleObject, ExamplesLibrary">
    <!-- setter injection using the ref attribute -->
    <property name="objectOne" ref="anotherExampleObject"/>    
    <property name="objectTwo" ref="yetAnotherObject"/>
    <property name="IntegerProperty" value="1"/>
</object>
<object id="anotherExampleObject" type="Examples.AnotherObject, ExamplesLibrary"/>
<object id="yetAnotherObject" type="Examples.YetAnotherObject, ExamplesLibrary"/>

C#

public class ExampleObject
{
  private AnotherObject objectOne;
  private YetAnotherObject objectTwo;
  private int i;
  
  public AnotherObject ObjectOne
  {
    set { this.objectOne = value; }
  }
  
  public YetAnotherObject ObjectTwo
  {
    set { this.objectTwo = value; }
  }
  
  public int IntegerProperty
  {
    set { this.i = value; }
  }  
}
上面的示例非学容易理解,从XML中可以看出其配置的name对应的属性关联,ref则对应类名,value为直接附值

2.使用静态工厂依赖注入:

<object id="exampleObject" type="Examples.ExampleFactoryMethodObject, ExamplesLibrary"
     factory-method="CreateInstance">
    <constructor-arg name="objectOne" ref="anotherExampleObject"/>
    <constructor-arg name="objectTwo" ref="yetAnotherObject"/>
    <constructor-arg name="intProp" value="1"/>
</object>
<object id="anotherExampleObject" type="Examples.AnotherObject, ExamplesLibrary"/>
<object id="yetAnotherObject" type="Examples.YetAnotherObject, ExamplesLibrary"/>
public class ExampleFactoryMethodObject
{
  private AnotherObject objectOne;
  private YetAnotherObject objectTwo;
  private int i;
  
// a private constructor
  private ExampleFactoryMethodObject()
  {
  }
  public static ExampleFactoryMethodObject CreateInstance(AnotherObject objectOne,
                               YetAnotherObject objectTwo,
                               int intProp)
  {
    ExampleFactoryMethodObject fmo = new ExampleFactoryMethodObject();
    fmo.AnotherObject = objectOne;
    fmo.YetAnotherObject = objectTwo;
    fmo.IntegerProperty = intProp;
    return fmo;
  }
  // Property definitions
}
上面类的注入方式已由属性变成了静态工厂方式,注意XML中的factory-method="CreateInstance",这里已经配置好了工厂方法的名称



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值