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 theuserPreferences bean definition for the lifetime of a single HTTPSession. In other words, the userPreferences bean is effectively scoped at the HTTPSession 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 HTTPSession instances that are also using instances created from the sameuserPreferences bean definition do not see these changes in state, because they are particular to an individual HTTPSession. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTPSession 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. Seethe section called “Choosing the type of proxy to create” andAppendix E,XML Schema-based configuration.) Why do definitions of beans scoped at therequest,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 followinguserPreferences 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!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章