編譯器:VS2013
.Net版本:.net framework4.5
Spring.Core.dll:1.3
Common.Logging
namespace CreateObjects { public class Person { public override string ToString() { return "我是Person類"; } public class Heart { public override string ToString() { return "我是Heart類"; } } } }
namespace CreateObjects { public class GenericClass<T> { } }
namespace CreateObjects { public static class StaticObjectsFactory { public static Person CreateInstance() { return new Person(); } } }
namespace CreateObjects { public class InstanceObjectsFactory { public Person CreateInstance() { return new Person(); } } }
<?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"></resource> </context> <objects> <!--構造器--> <object id="person" type="CreateObjects.Person,CreateObjects"></object> <!--嵌套類型--> <object id="heart" type="CreateObjects.Person+Heart,CreateObjects"></object> <!--泛型類型GenericClass<int>--> <object id="genericClass" type="CreateObjects.GenericClass<int>,CreateObjects"></object> <!--靜態工廠--> <object id="staticObjectsFactory" type="CreateObjects.StaticObjectsFactory,CreateObjects" factory-method="CreateInstance" ></object> <!--實例工廠--> <!--工廠--> <object id="instanceObjectsFactory" type="CreateObjects.InstanceObjectsFactory,CreateObjects"></object> <!--創建的對象--> <object id="instancePerson" factory-method="CreateInstance" factory-object="instanceObjectsFactory"></object> </objects> </spring> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
namespace CreateObjects { class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Person person = context.GetObject("person") as Person; Console.WriteLine(person); Person.Heart heart = context.GetObject("heart") as Person.Heart; Console.WriteLine(heart); GenericClass<int> genericClass = context.GetObject("genericClass") as GenericClass<int>; Console.WriteLine(genericClass); Person personStaticFactory = context.GetObject("staticObjectsFactory") as Person; Console.WriteLine(personStaticFactory); Person personInstanceFactory = context.GetObject("instancePerson") as Person; Console.WriteLine(personInstanceFactory); Console.ReadKey(); } } }