生命周期:
在每个Spring Ioc容器中的一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定bean节点的lazy-init="true"来延迟,这时候只有第一次获取bean时初始化bean:
<bean id="personService" class="com.river.service.impl.PersonServiceBean" lazy-init="true"/>
如果想对所有的bean都应用延迟初始化,则在beans加lazy-init="true",如下:
<beans lazy-init="true" ...>
测试:
在PersonServiceBean中的默认构造方法中加入:
public PersonServiceBean()
{
System.out.println("我被初始化了");
}
测试方法:
public void instanceSpring()
{
ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans.xml");
}
没加入lazy-init="true"时:
测试结果:我被初始化了
加入了lazy-init="true"时:
测试结果:无
bean作用域:
测试单实例:
bean:配置<bean id="personService" class="com.river.service.impl.PersonServiceBean" />
测试方法:
public void instanceSpring()
{
//RiverClassPathXMLApplicationContext ctx = new RiverClassPathXMLApplicationContext("beans.xml");
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService ps = (PersonService) ctx.getBean("personService");
PersonService ps1 = (PersonService) ctx.getBean("personService");
System.out.println(ps==ps1);
}
测试结果:true;
如希望每次的对象都是不同的 需改变其作用范围:
<bean id="personService" class="com.river.service.impl.PersonServiceBean" scope="prototype" />
其中prototype为每次一个不同对象。
测试:
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService ps = (PersonService) ctx.getBean("personService");
PersonService ps1 = (PersonService) ctx.getBean("personService");
System.out.println(ps==ps1);
结果 false;
在每个Spring Ioc容器中的一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定bean节点的lazy-init="true"来延迟,这时候只有第一次获取bean时初始化bean:
<bean id="personService" class="com.river.service.impl.PersonServiceBean" lazy-init="true"/>
如果想对所有的bean都应用延迟初始化,则在beans加lazy-init="true",如下:
<beans lazy-init="true" ...>
测试:
在PersonServiceBean中的默认构造方法中加入:
public PersonServiceBean()
{
System.out.println("我被初始化了");
}
测试方法:
public void instanceSpring()
{
ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans.xml");
}
没加入lazy-init="true"时:
测试结果:我被初始化了
加入了lazy-init="true"时:
测试结果:无
bean作用域:
测试单实例:
bean:配置<bean id="personService" class="com.river.service.impl.PersonServiceBean" />
测试方法:
public void instanceSpring()
{
//RiverClassPathXMLApplicationContext ctx = new RiverClassPathXMLApplicationContext("beans.xml");
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService ps = (PersonService) ctx.getBean("personService");
PersonService ps1 = (PersonService) ctx.getBean("personService");
System.out.println(ps==ps1);
}
测试结果:true;
如希望每次的对象都是不同的 需改变其作用范围:
<bean id="personService" class="com.river.service.impl.PersonServiceBean" scope="prototype" />
其中prototype为每次一个不同对象。
测试:
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService ps = (PersonService) ctx.getBean("personService");
PersonService ps1 = (PersonService) ctx.getBean("personService");
System.out.println(ps==ps1);
结果 false;