现在的位置: 首页 > 综合 > 正文

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

2013年10月07日 ⁄ 综合 ⁄ 共 1749字 ⁄ 字号 评论关闭

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",这里已经配置好了工厂方法的名称

抱歉!评论已关闭.