Spring中scope作用域



scope作用域:

   1.prototype

   2.request

     3.session

   4.singleton

   5.global session


1.prototype(多例)

   prototype作用域部署的bean,每一次请求(将其注入到另一个bean中,或者以程序的方式调用容器的 getBean()方法)都会产生一个新的bean实例,相当与一个new的操作。

   配置实例:

<bean id="happy" class="cn.hq.entlty.Student" scope="prototype"/>

  效果实现:

 

2.request

  request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效。

  配置实例(初始化web.xml中配置): 

<bean id="happy" class="cn.hq.entlty.Student" scope="request"/>

  web.xml

<web-app>
   ...
  <listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
   ...
</web-app>

  注意如果是Servlet2.4以前的web容器,那么你要使用一个javax.servlet.Filter的实现。

<web-app>
 ..
 <filter> 
    <filter-name>requestContextFilter</filter-name> 
    <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
 </filter> 
 <filter-mapping> 
    <filter-name>requestContextFilter</filter-name> 
    <url-pattern>/*</url-pattern>
 </filter-mapping>
   ...
</web-app>

3.session

     session作用域表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效。

    配置实例:前提和request相似在web.xml里进行配置

<bean id="happy" class="cn.hq.entlty.Student" scope="request"/>

4.singleton

   配置实例:

     单例,在Spring IoC容器中仅存在一个Bean实例(默认的scope),spring默认在spring容器中只有一个Bean实例对象。

5.global session

  配置实例:

  global session作用域类似于标准的HTTP Session作用域,不过它仅仅在基于portlet的web应用中才有意义。Portlet规范定义了全局Session的概念,它被所有构成某个 portlet web应用的各种不同的portlet所共享。在global session作用域中定义的bean被限定于全局portlet Session的生命周期范围内。如果你在web中使用global session作用域来标识bean,那么web会自动当成session类型来使用。

      注意:配置前提和request相同,配置web.xml


骏马是跑出来的,强兵是打出来的。

              ---真理

原文地址:https://www.cnblogs.com/hq-123/p/5993162.html