Spring.NET学习笔记7——依赖对象的注入(基础篇) Level 200

1.person类

 public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person Friend { get; set; }
    }

2. persondao类

 public class PersonDao
    {

        private Person argPerson;
        private int intProp;

        public PersonDao(Person argPerson, int intProp)
        {
            this.argPerson = argPerson;
            this.intProp = intProp;
        }

        public void Get()
        {
            //构造函数注入的整型参数
            Console.WriteLine(string.Format("intProp:{0}", intProp));

            //构造函数注入的Person
            Console.WriteLine(string.Format("argPerson Name:{0}", argPerson.Name));
            Console.WriteLine(string.Format("argPerson Age:{0}", argPerson.Age));

            //内联对象Friend
            Console.WriteLine(string.Format("argPerson Friend Name:{0}", argPerson.Friend.Name));
            Console.WriteLine(string.Format("argPerson Friend Age:{0}", argPerson.Friend.Age));

            //内联对象的循环引用
            Console.WriteLine(string.Format("argPerson Friend Friend Name:{0}", argPerson.Friend.Friend.Name));
            Console.WriteLine(string.Format("argPerson Friend Friend Age:{0}", argPerson.Friend.Friend.Age));
        }
    }

3.配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>

  <spring>

    <context>
      <resource uri="config://spring/objects" />
    </context>

    <objects xmlns="http://www.springframework.net">

      <object id="person" type="SpringNetDi.Person, SpringNetDi">
        <!--属性值类型注入-->
        <property name="Name" value="Liu Dong"/>
        <property name="Age" value="27"/>

        <!--内联对象注入-->
        <property name="Friend">
          <object type="SpringNetDi.Person, SpringNetDi">
            <property name="Name" value="Beggar"/>
            <property name="Age" value="23"/>
            <property name="Friend" ref="person"/>
          </object>
        </property>
        
      </object>

      <object id="personDao" type="SpringNetDi.PersonDao, SpringNetDi">
        <!--构造器注入-->
        <constructor-arg name="argPerson" ref="person"/>
        <constructor-arg name="intProp" value="1"/>
        
      </object>

    </objects>

  </spring>

</configuration>

4.调用

 class Program
    {
        static void Main(string[] args)
        {
            IApplicationContext ctx = ContextRegistry.GetContext();

            PersonDao dao = ctx.GetObject("personDao") as PersonDao;
            dao.Get();

            Console.ReadLine();
        }
    }

 

5.结果

 

posted on 2015-03-23 14:21  听哥哥的话  阅读(154)  评论(0编辑  收藏  举报

导航