Spring.Net Ⅰ.pp---浅尝

来源:互联网 发布:ni卸载软件 编辑:程序博客网 时间:2024/04/30 19:38

浅尝的感觉

感谢这篇博文:http://www.cnblogs.com/GoodHelper/archive/2009/10/25/Spring_NET_IoC.html

目前我的理解:

作用:在XML中配置/修改 实现类列表,使用实现类对象更为简单

你将一个接口的所有实现类名称都放在这个容器里,在代码中获取这个容器,输入一个实现类名称的字符串可以获取相应对象

好处:按设计来说,简单的需求变更下,高层模块修改的更简单了,也符合面向对象、面向接口编程

用时对比:【直接实例化对象】 vs 【加载Spring.Net配置 + 通过反射生成所需对象】

这里写图片描述


平台环境

  • .Net4.5
  • Spring.Net4.0

浅尝步骤

1.新建控制台、类库各一

2.类库代码如下:

//一个接口namespace SpringNetLesson01_Modles{    public interface ICompary    {        string GetCompanyName();    }}//一个实现类namespace SpringNetLesson01_Modles{    class MicrosoftCompany : ICompary    {        public string GetCompanyName()        {            return "Microsoft";        }    }}//一个实现类namespace SpringNetLesson01_Modles{    class AppleCompany : ICompary    {        public string GetCompanyName()        {            return "Apple";        }    }}

3.控制台引用

  • Common.Logging.dll
  • Spring.Core.dll
  • SpringNetLesson01_Modles

4.控制台代码如下

using System;using Spring.Context;using Spring.Context.Support;using SpringNetLesson01_Modles;namespace SpringNetLesson01{    class Program    {        static void Main(string[] args)        {            IocMethod();            Console.ReadLine();        }        private static void IocMethod()        {         //获取容器            IApplicationContext ctx = ContextRegistry.GetContext();            //输入Microsoft这个id来获取对象            ICompary company = ctx.GetObject("Microsoft") as ICompary;            if(!ReferenceEquals(null, company))                Console.WriteLine(@"Dear pp,Welcome {0},come on, join us",company.GetCompanyName());        }    }}

5.控制台添加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"/>     </context>    <objects xmlns="http://www.springframework.net">      <description>一个简单的控制反转例子</description>      <!--Id: 自定义命名          type: 命名空间 + 程序集-->      <object id="Microsoft" type="SpringNetLesson01_Modles.MicrosoftCompany, SpringNetLesson01_Modles"></object>      <object id="Apple" type="SpringNetLesson01_Modles.AppleCompany, SpringNetLesson01_Modles"></object>    </objects>  </spring><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

6.运行结果

这里写图片描述

7.错误配置(1):没有引用Common.Logging.dll

这里写图片描述

8.错误配置(2):App.config中有写错的地方(may lack a word)

这里写图片描述

0 0
原创粉丝点击