Asp.Net 熟悉 Spring

注:(为加强记忆,所以记录下来,对于有些地方为什么那样写,我也不太理解)

一、我们先创建个窗体应用程序Demos,事先熟悉它是这么实现的

  第一步,先在项目的根目录下建一个library文件夹,目的是放我们的用到的dll文件。现在练习spring就要这三个就可以了:

 

第二步,添加这两个引用之后,新建一个配置文件app.config文件,

<?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"/>
      <resource uri="file://Service.xml"/>
    </context>
    <objects xmlns="http://www.springframework.net">
      <!--<description>An  example that demonstrates simple IoC features.</description>
      <object name="UserInfo"  type="SpringNetTest.UerInfoService, SpringNetTest">
        <constructor-arg name="age" value="18"/>
        <property name="Name" value="老马"/>
      </object>-->
    </objects>
  </spring>
</configuration>

第三步, 创建一个userInfoService类和它的一个接口IUserInfoService

   public class UerInfoService:IUserInfoService
    {
        public UerInfoService(int age)
        {
            Age = age;
        }
        public int Age { get; set; }
        public string Name { get; set; }
        public void Show()
        {
            Console.Write("我说ok,你说"+Name);
            Console.WriteLine("构造函数参数注入 age"+Age);
        }
    }

第四步,在配置文件中加上自己的注入对象,也就是把上上图中的注释部分放开,也可以不在这个文件中添加,那就需要再创建一个xml文件,需要设置两个属相 “始终复制”,“嵌入到资源”

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <description>An  example that demonstrates simple IoC features.</description>
  <object name="UserInfo"  type="SpringNetTest.UerInfoService, SpringNetTest">
    <constructor-arg name="age" value="18"/>
    <property name="Name" value="老马"/>
  </object>
</objects>

第五步,准备工作做完,开始在form中测试我们的spring(将输出类型设置为控制台应用程序)

 private void button1_Click(object sender, EventArgs e)
        {
            IApplicationContext ctx = ContextRegistry.GetContext(); //获取容器
            IUserInfoService userInfoService =(IUserInfoService) ctx.GetObject("UserInfo"); //获取注入对象
            userInfoService.Show();
        }

 

posted @ 2017-03-18 11:29  disLike  阅读(296)  评论(0编辑  收藏  举报