操作系統:Win10
編譯器:VS2013
.Net版本:.net framework4.5
Spring.Core.dll:1.3.1
Common.Logging.dll
namespace SpringNetDi { public class Product { public string Name { get; set; } public decimal UnitPrice { get; set; } } }
namespace SpringNetDi { public class ProductFactory { public Product FactoryProduct { get; set; } } }
namespace SpringNetDi { public class Article { private string name; private string writer; public Article(string name, string writer) { this.name = name; this.writer = writer; } public void GetMsg() { Console.WriteLine("你好,我是" + writer); } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler,Spring.Core"></section> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler,Spring.Core"/> </sectionGroup> </configSections> <spring> <context> <resource uri="config://spring/objects"></resource> </context> <objects> <!--01屬性注入-值類型--> <object name =" product" type="SpringNetDi.Product,SpringNetDi"> <property name="Name" value="記號筆"></property> <property name="UnitPrice" value="5"></property> </object> <!--02屬性注入-引用類型--> <object name="factory" type="SpringNetDi.ProductFactory,SpringNetDi"> <property name="FactoryProduct" ref="product"></property> </object> <!--03構造函數注入--> <object name="article" type="SpringNetDi.Article,SpringNetDi"> <constructor-arg name="name" value="依賴注入"></constructor-arg> <constructor-arg name="writer" value="Kimisme"></constructor-arg> </object> </objects> </spring> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
namespace SpringNetDi { class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Product product = context.GetObject("product") as Product; Console.WriteLine(product.Name); ProductFactory factory = context.GetObject("factory") as ProductFactory; Console.WriteLine(factory.FactoryProduct.Name); Article article = context.GetObject("article") as Article; article.GetMsg(); Console.WriteLine("ok"); } } }