spring中有六种内置的scope,其中spring默认注册了五种。
分别为:singleton,prototype,request,session,gobalsession.其中后面三种只能在webApplicationContext中出现
还有一种实现是SimpleThreadScope,当并没有默认注册到spring的容器中去。
下面是一些分别的介绍:
(1)singleton:
单例,每个bean在同一个spring容器中只会有一个实例存在。这是spring内置的默认作用域。
当使用applicationContext.getBean(A.class)取得bean的时候,实际上每次的调用返回的是同一个实例。也就是说spring的容器会保持被其创建的singleton对象的引用。
下面是测试代码:
package com.zhaiyx.springCore.scope;
import org.springframework.stereotype.Service;
@Service
public class SingletonScopeService {
}
package com.zhaiyx.springCore.scope;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringScopeTest {
private static ApplicationContext context;
@BeforeClass
public static void createApplicationContext() {
context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
}
@Test
public void testSingletonScope() {
SingletonScopeService oneService = context
.getBean(SingletonScopeService.class);
SingletonScopeService anotherService = context
.getBean(SingletonScopeService.class);
Assert.assertTrue(oneService == anotherService);
}
}
(2)prototype:
在spring容器中可以有任意数量的Bean的实例的存在。也就是说,这个时候每次向spring容器去请求这个bean的时候,都会得到不相同的对应。spring容器只负责去创建bean,而不会去保存对于bean的引用。
但是要注意的是,如果scope为singleton的beanA依赖于该bean,那么在beanA构建完成以后,该singletonbean同样也构建完成,在A的生命周期内不会去发生变动,因为只有一次构建的机会。但是beanA与beanB同时依赖于一个prototypeScope的bean,那么这个bean在内存中就存在两个实例,会被初始化两次。
如果在每次调用的时候都需要一个prototype的实例,则可以参考使用method injection
下面是测试代码:
package com.zhaiyx.springCore.scope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeScopeService {
}
package com.zhaiyx.springCore.scope;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringScopeTest {
private static ApplicationContext context;
@BeforeClass
public static void createApplicationContext() {
context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
}
@Test
public void testPrototypeScope() {
PrototypeScopeService oneService = context
.getBean(PrototypeScopeService.class);
PrototypeScopeService anotherService = context
.getBean(PrototypeScopeService.class);
Assert.assertFalse(oneService == anotherService);
}
}
(3)request(只存在于WebApplicationContext中):
每一个request一个实例
(4)session(只存在于WebApplicationContext中):
每一个session一个实例
(5)gobalsession(只存在于WebApplicationContext中):
在servlet容器中,与session一样。