Spring Bean Scope (作用域)

本文详细介绍了Spring框架中Bean的几种作用域:singleton、prototype、request、session及globalsession,包括它们的特点、应用场景以及配置方式。对于singleton和prototype的区别进行了重点阐述。

singleton:

单例模式,针对每个spring容器,只有一个该类的实例被管理,每次调用此实例都是同一个对象被返回,所以适用于无状态bean。默认情况下,singleton作为spring容器中bean的作用域。

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>

prototype:

针对每一次bean调用,注入或者程序中显式调用getBean(...)类似方法,都有一个新的对象被初始化后返回,所以适用于有状态bean。值得注意的是尽管初始化回调方法依然会被调用,但是声明为prototype的bean的“销毁”回调方法不会被容器调用。spring container初始装配之后将控制权交给客户代码,客户代码需要承担释放资源的责任。(spring 提供prototype资源的释放方案,BeanPostProcessors)。

<!-- using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>

request,session,global session:

以上三种顾名思义,作用域分别是http request级别,session级别。spring context需要是web实现(比如:XmlWebApplicationContext)。DispatcherServlet/DispatcherPortlet,RequestContextListener 或RequestContextFilter 负责将每个http request/session 绑定到负责相应这个请求的线程上,并使得声名为request/session作用域的bean在后续调用中可用。

spring mvc

<servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

servlet 2.4+

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

servlet 2.3

<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>

 

refer to spring reference

转载于:https://www.cnblogs.com/dylanw/p/3678629.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值