对于自定义类型我们需要做些声明。下面的例子中 HelloWorld 需要 2 个构造参数,分别是一个自定义类型和 Type一定要注意,注入一个对象和一个 Type 的不同之处
using System;
using System.Collections;
using System.Text;
using System.Threading;
using Spring.Core;
using Spring.Context;
using Spring.Context.Support;
using System.Configuration;
namespace ConsoleApplication1.SpringNet
{
public class MyData
{
/// <summary>
/// 对于自定义类型我们需要做些声明。下面的例子中 HelloWorld 需要 2 个构造参数,分别是一个自定义类型和 Type
/// 一定要注意,注入一个对象和一个 Type 的不同之处
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "MyData...对象方法";
}
}
public class HelloWorld
{
private MyData data;
public HelloWorld(MyData data, Type type)
{
this.data = data;
Console.WriteLine(type);
}
public override string ToString()
{
return data.ToString();
}
}
public class Program
{
static void Main()
{
try
{
IApplicationContext context = ConfigurationSettings.GetConfig("spring/context") as IApplicationContext;
object o = context.GetObject("HelloWorld");
Console.WriteLine(o);
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
}
}
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<object id="HelloWorld" type="ConsoleApplication1.SpringNet.HelloWorld,test5">
<constructor-arg name="data" ref="MyData" />
<!--采用内联方式
<constructor-arg name="data" >
<object type="ConsoleApplication1.SpringNet.MyData, test5"/>
</constructor-arg>
-->
<constructor-arg name="type" value="ConsoleApplication1.SpringNet.MyData,test5" />
</object>
<object id="MyData" type="ConsoleApplication1.SpringNet.MyData, test5" />
</objects>
</spring>