您的位置:首页 > 编程语言 > Java开发

Spring.Net Ⅰ.pp---浅尝

2016-05-27 16:30 519 查看

浅尝的感觉

感谢这篇博文: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)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: