Spring 4.3中为Bean的实例定义了7种作用域。
作用域名称 | 说明 |
---|---|
singleton (单例) | 使用singleton定义的Bean在Spring容器中将只有一个实例,也就是说,无论有多少个Bean引用它,始终将指向同一个对象。这也是Spring容器默认的作用域。 |
prototype (原型) | 每次通过Spring容器获取的prototype定义的Bean时,容器都将创建一个新的Bean实例。 |
request | 在一次HTTP请求中,容器会返回该Bean的同一个实例。对不同的HTTP请求则会产生一个新的Bean,而且该Bean仅会在当前的HTTP Request内有效。 |
session | 在一次新的HTTP Session中,容器会返回该Bean的同一个实例。对不同的HTTP请求则会产生一个新的Bean,而且该Bean仅会在当前的HTTP Session内有效。 |
globalSession | 在一个全局的HTTP Session中,容器会返回该Bean的同一个实例。仅在protlet上下文时有效。 |
application | 为每个ServletContext对象创建一个实例。仅在Web相关的ApplicationContext中生效。 |
websocket | 为每个websocket对象创建一个实例。仅在Web相关的ApplicationContext中生效。 |
singleton作用域测试
在项目中,创建一个包,包中创建一个Scope类,该类不需要写任何方法。然后在该包中创建一个配置文件beans4.xml。最后在包中创建一个测试类ScopeTest,来测试singleton作用域。
/*beans4.xml配置文件内容*/
<bean id="scope" class="my.scope.Scope" scope="singleton"/>
/*ScopeTest.java测试类内容*/
package my.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest{
public static void main(String[] args){
//定义配置文件路径
String xmlPath = “my/scope/beans4.xml”;
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//输出获得实例
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
}
/*执行后,控制台结果为
my.scope.Scope@e9a892
my.scope.Scope@e9a892
两次结果相同,说明Spring容器只创建了一个Scope类的实例。
当beans4.xml文件中不设置 scope="singleton"时,也可以,因为Spring默认作用域为singleton
*/
prototype作用域
对需要保持会话状态的Bean应使用prototype作用域。在使用prototype作用域时,spring容器会为每个Bean请求都创建一个新的实例。
/*beans4.xml配置文件内容*/
<bean id="scope" class="my.scope.Scope" scope="prototype"/>
/*ScopeTest.java测试类内容*/
package my.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeTest{
public static void main(String[] args){
//定义配置文件路径
String xmlPath = “my/scope/beans4.xml”;
//加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//输出获得实例
System.out.println(applicationContext.getBean("scope"));
System.out.println(applicationContext.getBean("scope"));
}
}
/*执行后,控制台结果为
my.scope.Scope@fbd816
my.scope.Scope@2bcfcb
两次结果不相同,说明Spring容器只创建了两个Scope类的实例。
*/
注意:此时当beans4.xml文件中不设置 scope="singleton"时,不可以,因为Spring默认作用域为singleton,而并非prototype。