- singleton
默认情况下,在容器启动时初始化Bean。可以指定bean节点的lazy-init="true"来延迟初始化bean,此时只有在第一次获取Bean才会初始化bean。 如:
<bean id="myid" class="xxx" lazy-init="true"/>
如果想对所有Bean都应用延迟初始化,可以在根节点beans设置default-lazy-init="true",如:
<beans default-lazy-init="true" ...>
- prototype
- request
- session
- global session
简单验证一下singleton和prototype作用域。借用前面的例子,
<bean id="personService" class="com.spring.test.manager.impl.PersonManager" />
不特别指定scope,则默认情况下scope="singleton"
package com.spring.test.junit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.test.manager.IPersonService;
public class PersonServiceTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring.xml");
IPersonService personService = (IPersonService) ctx
.getBean("personService");
IPersonService personService2 = (IPersonService) ctx
.getBean("personService");
System.out.println(personService == personService2);
}
}
运行此junit test class,控制台打印true,证明即便多次获取同一个bean,这些bean仍指向内存中同一地址,为同一对象实例。
现在,将上面的bean的作用域修改为prototype。
<bean id="personService" class="com.spring.test.manager.impl.PersonManager" scope="prototype"/>
再次运行上面的junit test class,控制台返回false,证明多次获取同一个bean,容器会生成新的对象实例返回。
No comments:
Post a Comment