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
- Spring.Net Ⅰ.pp---浅尝
- Spring MVC浅尝
- 浅尝
- pp
- PP
- pp
- pp
- 看pp说pp
- PhotoShop浅尝
- CorelDRAW浅尝
- 浅尝触发器
- 浅尝DotNetNuke
- 浅尝Linux
- 浅尝JQchart!
- DWR浅尝
- 浅尝Mina
- 浅尝python
- 浅尝Kivy
- 为github帐号添加SSH keys
- python05-函数的位置参数、默认参数、可变参数、键值对参数(关键字参数)
- Android开发之消息机制详解(1)线程间的通信handler
- leetcode 328 Odd Even Linked List(调整链表使得奇数位置的元素位于偶数位置元素之前)
- 二维码推广网站
- Spring.Net Ⅰ.pp---浅尝
- [Spring] - Property注入
- 移动无线网络演进历史
- Android-PullToRefresh
- 获取sd卡剩余内存
- with的用法小结
- 抓取图片到本地,你会用到什么函数
- qt-一个类连接两个界面
- CodeForces-55B-Smallest number(暴力深搜)