spring Scope

1. singleton

Only one shared instance of a singleton bean  is managed, and all requests for beans  with an id or ids matching that  bean definition result in that one specific bean instance being returned by the Spring container.

To put it another way, when you defin a bean definition and it is scope as a singleton, the Spring IoC container create exactly one instance of the object  define by that bean  definition. This singleton instance is stored in a cache of such singleton beans, and all subsequence requests and references for that named bean return the cached object.

hehe

在 Spring 容器中 singleton bean 仅有一个共享实例,所有被请求的bean 的 id 或者多个id 中与所定义的singleton bean 匹配, Spring 容器将返回同一个指定的实例。

或者说,当你定义一个bean 且它是 singleton bean,Spring IoC将会仅创建一个定义好的对象实例,这个单例实例存储在单例缓存中,并且随后所有对这个bean的请求或引用,都将返回这个被缓存的对象。


Spring's concept of a singleton differs from the Singleton pattern of Gang of Four( GoF ) patterns of book. The GoF Singleton hard-codes the scope of the object such that one and only one instance of a particular class is created per ClassLoader. The Scope of the spring singleton is best described as per container and per instance. This means that if you define one bean for a particular class in single Spring container, then the spring container creates one and only one instance of the class define by that bean definition. The Singleton Scope is the default scope in Spring.


Note:

    When you use a singleton bean with dependencies on prototype beans, be aware that dependencies are resolved  at instantiation time. Thus if you dependency inject a prototype-scope bean  into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-indected into singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.


However if you want the singleton-scoped bean  to acquire a new instance of the prototype-scoped bean  repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton-scoped bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.


But you can resolve this problem like that:

spring Singleton-scoped Bean with dependecies on prototype-scoped Bean 


Initial web configuration

To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans. (This initial setup isnot required for the standard scopes, singleton and prototype.)

How you accomplish this initial setup depends on your particular Servlet environment..

If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the SpringDispatcherServlet, orDispatcherPortlet, then no special setup is necessary:DispatcherServlet andDispatcherPortlet already expose all relevant state.

If you use a Servlet 2.4+ web container, with requests processed outside of Spring's DispatcherServlet (for example, when using JSF or Struts), you need to add the followingjavax.servlet.ServletRequestListener to the declarations in your web applicationsweb.xml file:

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

If you use an older web container (Servlet 2.3), use the provided javax.servlet.Filter implementation. The following snippet of XML configuration must be included in theweb.xml file of your web application if you want to access web-scoped beans in requests outside of Spring's DispatcherServlet on a Servlet 2.3 container. (The filter mapping depends on the surrounding web application configuration, so you must change it as appropriate.)


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

DispatcherServlet, RequestContextListener andRequestContextFilter all do exactly the same thing, namely bind the HTTP request object to theThread that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.


Request scope
<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

The Spring container creates a new instance of the LoginAction bean by using theloginAction bean definition for each and every HTTP request. That is, theloginAction bean is scoped at the HTTP request level. You can change the internal state of the instance that is created as much as you want, because other instances created from the sameloginAction bean definition will not see these changes in state; they are particular to an individual request. When the request completes processing, the bean that is scoped to the request is discarded.


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

The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that other HTTP Session instances that are also using instances created from the same userPreferences bean definition do not see these changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.


Global session scope
<bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession"/>

The global session scope is similar to the standard HTTPSession scope (described above), and applies only in the context of portlet-based web applications. The portlet specification defines the notion of a globalSession that is shared among all portlets that make up a single portlet web application. Beans defined at theglobal session scope are scoped (or bound) to the lifetime of the global portletSession.

If you write a standard Servlet-based web application and you define one or more beans as havingglobal session scope, the standard HTTPSession scope is used, and no error is raised.

Scoped beans as dependencies
The Spring IoC container manages not only the instantiation of your objects (beans), but also the wiring up of collaborators (or dependencies). If you want to inject (for example) an HTTP request scoped bean into another bean, you must inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real, target object from the relevant scope (for example, an HTTP request) and delegate method calls onto the real object.

Note:

    You do not need to use the <aop:scoped-proxy/> in conjunction with beans that are scoped as singletons or prototypes.


The configuration in the following example is only one line, but it is important to understand thewhy as well as thehow behind it.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">

  <!-- an HTTP Session-scoped bean exposed as a proxy -->
  <bean id="userPreferences" class="com.foo.UserPreferences" scope="session">

        <!-- instructs the container to proxy the surrounding bean -->
        <aop:scoped-proxy/>
  </bean>

  <!-- a singleton-scoped bean injected with a proxy to the above bean -->
  <bean id="userService" class="com.foo.SimpleUserService">

      <!-- a reference to the proxied userPreferences bean -->
      <property name="userPreferences" ref="userPreferences"/>

  </bean>
</beans>

To create such a proxy, you insert a child <aop:scoped-proxy/> element into a scoped bean definition. See the section called “Choosing the type of proxy to create” and Appendix E,XML Schema-based configuration.) Why do definitions of beans scoped at the request, session, globalSession and custom-scope levels require the <aop:scoped-proxy/> element ? Let's examine the following singleton bean definition and contrast it with what you need to define for the aforementioned scopes. (The following userPreferences bean definition as it stands is incomplete.)


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

<bean id="userManager" class="com.foo.UserManager">
  <property name="userPreferences" ref="userPreferences"/>
</bean>

In the preceding example, the singleton bean userManager is injected with a reference to the HTTPSession-scoped beanuserPreferences. The salient point here is that theuserManager bean is a singleton: it will be instantiatedexactly once per container, and its dependencies (in this case only one, theuserPreferences bean) are also injected only once. This means that theuserManager bean will only operate on the exact sameuserPreferences object, that is, the one that it was originally injected with.

This is not the behavior you want when injecting a shorter-lived scoped bean into a longer-lived scoped bean, for example injecting an HTTPSession-scoped collaborating bean as a dependency into singleton bean. Rather, you need a singleuserManager object, and for the lifetime of an HTTPSession, you need a userPreferences object that is specific to said HTTPSession. Thus the container creates an object that exposes the exact same public interface as theUserPreferences class (ideally an object thatis a UserPreferences instance) which can fetch the realUserPreferences object from the scoping mechanism (HTTP request,Session, etc.). The container injects this proxy object into theuserManager bean, which is unaware that thisUserPreferences reference is a proxy. In this example, when aUserManager instance invokes a method on the dependency-injectedUserPreferences object, it actually is invoking a method on the proxy. The proxy then fetches the realUserPreferences object from (in this case) the HTTPSession, and delegates the method invocation onto the retrieved realUserPreferences object.

Thus you need the following, correct and complete, configuration when injectingrequest-,session-, andglobalSession-scoped beans into collaborating objects:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
  <aop:scoped-proxy/>
</bean>

<bean id="userManager" class="com.foo.UserManager">
  <property name="userPreferences" ref="userPreferences"/>
</bean>


本来想把它全部翻译出来的,但是由于时间关系未能做到 ,先出个部分版的。路 过的若觉得 翻译得不行请联系 QQ:492788802!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值