Spring Bean Scope (作用域)

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

上一篇:java 异常匹配


下一篇:Spring bean - scope详解