Introduction to the five scopes of beans in spring (reproduced)

Source: Internet
Author: User

The last version of the IOC container in spring supports two different bean scopes (singleton and prototype).
Spring 2.0 improves this by not only providing additional scopes that rely on the spring deployment environment (for example, request and session scope beans in a web environment), but also providing the so-called ' hooks ' (' hooks ' ) (Because a better representation is not found) enables spring users to create their own scopes.

It should be noted that the above changes are transparent to the end user, even though the basic (intrinsic) implementation of the Singleton and prototype scope beans has changed. The existing configuration does not need to be changed or discarded.


How to use the scope of spring:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "singleton"/>


Here's a description of the scope in spring, respectively:

1. Singleton scope

When the scope of a bean is set to Singleton, only one shared bean instance exists in the spring IOC container, and all requests to the bean, as long as the ID matches the bean definition, will return only the same instance of the bean. In other words, when a bean definition is set to singleton scope, the Spring IOC container only creates a unique instance of the bean definition. This single instance is stored in the singleton cache (singleton cache), and all subsequent requests and references to the bean will return the cached object instance, noting that the singleton in the singleton scope and GOF design pattern is completely different, The singleton design pattern indicates that only one class exists in a ClassLoader, and here the singleton represents a container for a bean, which means that when a bean is identified as Singleton, Only one of the beans will exist in spring's IOC container.

Configuration instance:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "singleton"/>

Or

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" singleton= "true"/>

2, prototype

Prototype-scoped beans, each request (injecting it into another bean or programmatically invoking the container's Getbean () method) produces a new instance of the bean, which is equivalent to the operation of an For prototype-scoped beans, it is important to note that spring cannot be responsible for the entire life cycle of a prototype bean, which is given to the client after it is initialized, configured, decorated, or assembled with a prototype instance. The prototype instance is then ignored. Regardless of the scope, the container invokes the initialization lifecycle callback method for all objects, and for prototype, any configured destructor life-cycle callback methods will not be called. Clearing prototype-scoped objects and releasing expensive resources held by any prototype bean is the responsibility of the client code. (One possible way for the spring container to release the resource that is consumed by the singleton scope Bean is by using the bean's post processor, which holds a reference to the bean to be purged.) )

Configuration instance:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "prototype"/>

Or

<beanid= "Role" class= "Spring.chapter2.maryGame.Role" singleton= "false"/>


3. Request

The request indicates that a new bean will be generated for each HTTP request, and that the bean is only valid within the current HTTP requests, configuring the instance:

When the request, session, global session is used, the following configuration is first done in Web. XML, which initializes it:

If you are using a Web container of servlet 2.4 and above, you only need to add the following contextlistener to the Web application's XML declaration file:

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

If you are Servlet2.4 a previous web container, then you need to use a Javax.servlet.Filter implementation:

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

You can then configure the scope of the bean:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Request"/>

4. Session

The session scope indicates that a new bean is generated for each HTTP request, and that the bean is valid only within the current HTTP session, configuring the instance:

Configuration instance:

As with the request configuration instance, configuring the Web boot file can be configured as follows:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Session"/>

5. Global session

The global session scope is similar to the standard HTTP session scope, but it only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global session, which is shared by all the various portlets that make up a portlet Web application. The bean defined in the global session scope is limited to the lifetime of the world Portlet session. If you use the global session scope to identify the bean in the Web, the Web is automatically used as the session type.

Configuration instance:

As with the request configuration instance, configuring the Web boot file can be configured as follows:

<bean id= "Role" class= "Spring.chapter2.maryGame.Role" scope= "Global Session"/>

6. Custom Bean Assembly Scope

In spring 2.0, scopes can be arbitrarily extended, you can customize scopes, and even you can redefine existing scopes (but you can't overwrite Singleton and prototype), The scope of spring is defined by the interface Org.springframework.beans.factory.config.Scope, as long as the interface is implemented, and the following is an example:

We set up a scope for a thread that is valid in representing a thread with the following code:

Publicclass MyScope implements Scope ... {privatefinal ThreadLocal threadscope = new ThreadLocal () ... {protected Object initialvalue () ... {returnnew HashMap ();} }; Public Object Get (String name, Objectfactory objectfactory) ... {Map scope = (map) threadscope.get (); Object object = Scope.get (name); if (object==null) ... {object = Objectfactory.getobject (); Scope.put (name, object);} return object; } public Object Remove (String name) ... {Map scope = (map) threadscope.get (); return scope.remove (name);} Publicvoid Registerdestructioncallback (String name, Runnable callback) ... {}public String Getconversationid () ... {//TODO auto-generated method stubreturnnull;} }

Introduction to the five scopes of beans in spring (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.