天天看点

Spring-scope详解

Spring中的scope配置

xml方式

Spring-scope详解

注解方式

Spring-scope详解

scope类型

  1. singleton(单一实例)

    此取值时表明容器中创建时只存在一个实例,所有引用此 bean 都是单一实例。

    此外,singleton 类型的 bean 定义从容器启动到第一次被请求而实例化开始,只要容器不销毁或退出,该类型的 bean 的单一实例就会一直存活,典型单例模式,如同 servlet 在 web 容器中的生命周期。

  2. prototype

    Spring 容器在进行输出 prototype 的 bean 对象时,会每次都重新生成一个新的对象给请求方

  3. request

    request,session 和 global session 类型只实用于 web 程序,通常是和 XmlWebApplicationContext 共同使用。

    xml<bean id ="requestPrecessor" class="...RequestPrecessor" scope="request" />

    XmlWebApplicationContext 会为每个 HTTP 请求创建一个全新的 RequestPrecessor 对象,当请求结束后,该对象的生命周期即告结束,如同java web中request的生命周期。当同时有100个HTTP请求进来的时候,容器会分别针对这10个请求创建10个全新的 RequestPrecessor 实例,且他们相互之间互不干扰,简单来讲,request 可以看做 prototype 的一种特例,除了场景更加具体之外,语意上差不多。
  4. session

    对于 web 应用来说,放到 session 中最普遍的就是用户的登录信息,对于这种放到 session 中的信息,我们可以使用如下形式的制定scope为session:

    <bean id ="userPreferences" class="...UserPreferences" scope="session" />

    Spring 容器会为每个独立的 session 创建属于自己的全新的 UserPreferences 实例,比 request scope 的bean会存活更长的时间,其他的方面没区别,如 java web中session的生命周期。
  5. global session

    <bean id ="userPreferences" class="...UserPreferences" scope="globalsession" />

    global session 只有应用在基于 porlet 的 web 应用程序中才有意义,它映射到 porlet 的 global 范围的 session,如果普通的 servlet 的 web 应用中使用了这个 scope,容器会把它作为普通的 session 的 scope 对待。

参考文章:

https://www.cnblogs.com/liaojie970/p/8302749.html

继续阅读