Spring.NET教程(四)——容器中对象的作用域(基础篇)
<!--单例模式-->
<object id="personDao" type="SpringNetScop.PersonDao, SpringNetScop" />
CreateWithSingleton
[Test]
public void CreateWithSingleton()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScop/SpringNetScop/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object obj1 = factory.GetObject("personDao");
object obj2 = factory.GetObject("personDao");
Assert.AreEqual(obj1, obj2);
}
我们用NUnit可以看到下图:
使用singleton="false"的代码
<!--非单例模式-->
<object id="person" type="SpringNetScop.Person, SpringNetScop" singleton="false" />
CreateWithOutSingleton
[Test]
public void CreateWithOutSingleton()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScop/SpringNetScop/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object obj1 = factory.GetObject("person");
object obj2 = factory.GetObject("person");
Assert.AreNotEqual(obj1, obj2);
}
Person
public class Person
{
public Person()
{
Console.WriteLine("Person被实例");
}
public override string ToString()
{
return "我是Person";
}
~Person()
{
Console.WriteLine("Person被销毁");
图为:
![Spring.NET教程(五)——容器中对象的作用域(基础篇)](http://img.ddvip.com/2009_10_26/1256547535_ddvip_7467.bmp)
这说明singleton=false后,每次调用GetObject方法获取的对象是不同实例的,当脱离调用方法(CreateWithOutSingleton)的作用域后,该实例会被Spring.NET容器销毁。
lazy-init属性是指:当Spring.NET容器初始化的时候标注该属性的对象将被实例化,反之则是调用GetObject方法的时候才被实例化。
<!--调用时加载-->
<object id="personServer" type="SpringNetScop.PersonServer, SpringNetScop" lazy-init="true" />
CreateWithLazy
[Test]
public void CreateWithLazy()
{
string[] xmlFiles = new string[]
{
"assembly://SpringNetScop/SpringNetScop/Objects.xml"
};
IApplicationContext context = new XmlApplicationContext(xmlFiles);
IObjectFactory factory = (IObjectFactory)context;
object dao = factory.GetObject("personDao");
Console.WriteLine(dao.ToString());
object server = factory.GetObject("personServer");
Console.WriteLine(server.ToString());
}
PersonServer
public class PersonServer
{
public PersonServer()
{
Console.WriteLine("PersonServer被实例");
}
public override string ToString()
{
return "我是PersonServer";
}
}
如图:
![Spring.NET教程(五)——容器中对象的作用域(基础篇)](http://img.ddvip.com/2009_10_26/1256547535_ddvip_2195.bmp)
PersonDao类未设置lazy-init属性,则当Spring.NET初始化时被实例;PersonServer类设置lazy-init="true",则当调用GetObject方法时才被实例。
一般情况下可以有选择的设置lazy-init属性,正如双刃剑一样,设置为lazy-init=true的时候应用程序启动时会快一点,但是在启动的时候就不能够帮我们检测错误,但当调用的时候一旦发生错误,后果是不堪设想的。
更多资料请查看Spring.NET中文手册。