一、开发环境
编译器:VS2013
.Net版本:.net framework4.5
二、涉及程序集
Spring.Core.dll:1.3
Common.Logging
三、开发过程
1.项目结构
2.添加Person.cs
namespace CreateObjects
{
public class Person
{
public override string ToString()
{
return "我是Person类";
}
public class Heart
{
public override string ToString()
{
return "我是Heart类";
}
}
}
}
3.添加GenericClass.cs
namespace CreateObjects
{
public class GenericClass<T>
{
}
}
4.添加StaticObjectsFactory.cs
namespace CreateObjects
{
public static class StaticObjectsFactory
{
public static Person CreateInstance()
{
return new Person();
}
}
}
5.添加InstanceObjectsFactory.cs
namespace CreateObjects
{
public class InstanceObjectsFactory
{
public Person CreateInstance()
{
return new Person();
}
}
}
6.配置Spring.Net
<?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>
7.控制台程序如下
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();
}
}
}