一、概要
scope 用来配置 spring bean 的作用域。
-
在spring2.0之前,bean只有2种作用域:singleton(单例)、non-singleton(也称 prototype)。
-
Spring2.0以后,增加了session、request、global session三种专用于Web应用程序上下文的Bean。
二、可选值
类型 | 说明 |
---|---|
singleton | 默认值,在Spring IoC容器中仅存在一个Bean实例,Bean以单实例的方式存在 |
prototype | 每次从容器中调用Bean时,都返回一个新的实例 |
request | 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境 |
session | 同一个HTTP session共享一个Bean,不同的HTTP session使用不同的Bean,该作用域仅适用于WebApplicationContext环境 |
globalSession | 同一个全局Session共享一个Bean,一般用于Portlet环境,该作用域仅适用于WebApplicationContext环境 |
三、可选值详解
singleton(单例)
说明
当一个bean的 作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。换言之,当把 一个bean定义设置为singleton作用域时,Spring IOC容器只会创建该bean定义的唯一实例。这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都 将返回被缓存的对象实例,这里要注意的是singleton作用域和GOF设计模式中的单例是完全不同的,单例设计模式表示一个ClassLoader中 只有一个class存在,而这里的singleton则表示一个容器对应一个bean,也就是说当一个bean被标识为singleton时候,spring的IOC容器中只会存在一个该bean,如果不希望在容器启动时提前实例化singleton的Bean,可以使用lazy-init属性进行控制
栗子
<bean id="user" class="com.wener.example.bean.User" scope="singleton"/>
// 或者
<bean id="user" class="com.wener.example.bean.User" singleton="true"/>
private static void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserDao dao = context.getBean("userDao", UserDao.class);
UserDao dao1 = (UserDao) context.getBean("userDao");
System.out.println(dao);
System.out.println(dao1);
}
// 两次输入的内存地址一致,说明是同一个对象
// com.wener.example.dao.impl.UserDaoImpl@46fa7c39
// com.wener.example.dao.impl.UserDaoImpl@46fa7c39
prototype
说明
设置为scope=”prototype”之后,每次调用getBean()都会返回一个新的实例
默认情况下,容器在启动时不会实例化prototype的Bean
Spring容器将prototype的Bean交给调用者后就不再管理它的生命周期
栗子
<bean id="user"
class="com.wener.example.bean.User"
scope="prototype">
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user = context.getBean("user", User.class);
User user1 = context.getBean("user",User.class);
System.out.println(user);
System.out.println(user1);
// 两次输入的内存地址不一样
// com.wener.example.bean.User@46fa7c39
// com.wener.example.bean.User@1fb700ee
网友评论