Spring.net IOC 依赖注入
Spring.net IOC 依赖注入
在配置文件(模版)中对对象属性进行预赋值,然后通过模版创建出来的对象的属性就有了对应的值。
目录
一、引用Spring.Core.dll,Common.Logging.dll
二、新建接口IPerson,新建类Person,Language
三、配置App.config,person1.xml,languages.xml
四、调用
一、引用Spring.Core.dll,Common.Logging.dll这个不具体说明了。
二、新建接口IPerson,新建类Person,Language
接口:IPerson
public interface IPerson { void Hello(); }
类:Language
public class Language { public string Name { get; set; } }
类:Person
public class Person :IPerson { public string Name { get; set; } public List<Language> ListLanguage { get; set; } public void Hello() { Console.WriteLine("Hello My Name is {0}", this.Name); Console.WriteLine("I will have several languages"); Console.Write("They are "); if (ListLanguage != null) { foreach (var item in ListLanguage) { Console.Write(item.Name +"\t"); } } } }
三、配置App.config,person1.xml,languages.xml
配置app.config
<!--引用Spring--> <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> <!--指向ioc/person1.xml文件--> <resource uri="ioc/person1.xml"></resource> <resource uri="ioc/languages.xml"></resource> </context> </spring>
配置person1.xml
<?xml version="1.0" encoding="utf-8"?> <objects xmlns="http://www.springframework.net"> <object name="person1" type="SpringIOC.Person,SpringIOC"> <property name="Name" value="Tom"/> <property name="ListLanguage"> <list> <ref object="language1"></ref> <ref object="language2"></ref> <ref object="language3"></ref> </list> </property> </object> </objects>
配置languages.xml
<?xml version="1.0" encoding="utf-8"?> <objects xmlns="http://www.springframework.net"> <object name="language1" type="SpringIOC.Language,SpringIOC"> <property name="Name" value="C#"/> </object> <object name="language2" type="SpringIOC.Language,SpringIOC"> <property name="Name" value="C++"/> </object> <object name="language3" type="SpringIOC.Language,SpringIOC"> <property name="Name" value="Java"/> </object> </objects>
四、调用
static void Main(string[] args) { IApplicationContext ctx = ContextRegistry.GetContext(); IPerson _person = ctx.GetObject<IPerson>("person1"); if (_person != null) { _person.Hello(); } Console.Read(); }
效果图
代码下载 https://files.cnblogs.com/files/cppwen/SpringIOC.rar