Spring.Net Ⅰ.pp---淺嘗

淺嘗的感覺

感謝這篇博文: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)

這裏寫圖片描述

發佈了206 篇原創文章 · 獲贊 123 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章