Spring Bean Scope (做用域)

singleton:html

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

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

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

<!-- 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:mvc

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

spring mvcui

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

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

servlet 2.3spa

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

相关文章
相关标签/搜索