Scope of Spring Bean

Source: Internet
Author: User

Scope of Spring Bean
Scope Description

Singleton

A bean definition corresponds to an object instance in each spring IOC container.

Prototype

A bean definition corresponds to multiple object instances.

Request

In an HTTP request, a bean definition corresponds to an instance, that is, each HTTP request will have its own bean instance, which is created from a bean definition. This scope is valid only in the Web-based spring ApplicationContext scenario.

Session

In an HTTP Session , a bean definition corresponds to an instance. This scope is valid only in the Web-based spring ApplicationContext scenario.

Global session

In a global HTTP Session , a bean definition corresponds to an instance. Typically, this is only valid when using the Portlet context. This scope is valid only in the Web-based spring ApplicationContext scenario.

Singleton scope

When a bean is scoped to Singleton, there will only be one shared bean instance in the spring IOC container, and all requests to the bean will only return the same instance of the bean as long as the ID matches that bean definition.

In other words, when a bean definition is set to Singlton 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 pins

Subsequent requests and references to the bean will return the cached object instance.

Prototype scope

A prototype-scoped bean causes getBean() A new bean instance to be created each time a request is made to the bean, either by injecting it into another bean or by programmatically invoking the container's method. On the basis of experience, the

A stateful bean should use the prototype scope, whereas a stateless bean should use the singleton scope.

Other scopes

    request, session and global session only in Web-based apps (you don't have to worry about what Web application framework you're using).

Attention

The scopes described below are only useful when using a web-based spring ApplicationContext implementation, such as XmlWebApplicationContext . If you are in a normal spring IOC container, such asXmlBeanFactory

Or ClassPathXmlApplicationContext , try to use these scopes, you will get an IllegalStateException exception (unknown bean scope).

   Initializing the Web configuration

    To use request , session and scoped global session beans (that is, a bean with a web scope), a small amount of initial configuration is done before the bean definition is set to begin. Note that this extra setting is not required if you only want "regular" scopes, that is, Singleton and prototype.

In the present case, there are several ways to accomplish this initial setup, depending on your particular servlet environment. If you are using a Web container of servlet 2.4 and above, you only need to add the following in the XML declaration file for your web App web.xml ContextListener

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

If you are using an earlier version of the Web container (Servlet 2.4 ago), then you need to use an javax.servlet.Filter implementation. Take a look at the following Web. XML configuration Fragment:

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

RequestContextListenerAnd the RequestContextFilter two classes do the same thing: Bind the HTTP Request object to the service for that request Thread . This allows the bean with the request and session scope to be accessed in the subsequent call chain.

Request Scope<bean id= "loginaction" class= "com.foo.LoginAction" scope= "Request"/>

For each HTTP request, the Spring container loginAction creates a completely new bean instance based on the bean definition, LoginAction and the loginAction Bean instance is valid only within the current HTTP request, so you can safely change the internal state of the built instance as needed. In other requests loginAction , instances created from the bean definition will not see these changes in status specific to a request. When the processing request ends, the bean instance of the request scope is destroyed.

Session scope

<bean id= "userpreferences" class= "Com.foo.UserPreferences" scope= "Session"/>

For an HTTP Session , the Spring container userPreferences creates a completely new bean instance based on the bean definition userPreferences , and the userPreferences Bean is valid only within the current HTTP Session . With the request作用域 same, you can safely change the internal state of the created instance as needed, and other HTTP Session based on userPreferences the created instance will not see these Session status changes specific to an HTTP. When HTTP Session is eventually discarded, the beans within that HTTP Session scope are discarded.

Global Session Scope

<bean id= "userpreferences" class= "com.foo.UserPreferences" scope= "Globalsession"/>

global sessionScopes are similar to standard HTTP Session scopes, but they are only meaningful in portlet-based Web applications. The Portlet specification defines the global Session concept, which is shared by all the different portlets that make up a portlet Web application. Beans defined in the scope global session are scoped to Session the life cycle of the global portlet.

Note that if you are writing a standard servlet-based Web application and you have defined one or more global session scoped beans, the system will use the standard HTTP Session scope and will not cause any errors.

Scope Beans and dependencies

It is good to be able to define the bean in an HTTP request or Session even a custom scope, but the spring IOC container is instantiated in addition to the management object (bean) and also the collaborator (or dependency) instantiation. If you are going to inject an HTTP request range bean into another bean, you need to inject an AOP proxy to replace the injected scope bean. That is, you need to inject a proxy object that has the same public interface as the Proxied object, and the container can be smart enough to get the real target object from the relevant scope (such as an HTTP request) and delegate the method invocation to the actual object.

Attention

<aop:scoped-proxy/>cannot be singleton prototype used with a bean that is scoped or. Creating a scoped proxy for the singleton Bean throws an BeanCreationException exception.

Let's look at the configuration of the dependent scope bean as a dependency, the configuration is not complex (only one row), but it is important to understand why and how.

<BeanID= "Userpreferences"class= "Com.foo.UserPreferences"Scope= "Session"> <Aop:scoped-proxy/>     </Bean>          <BeanID= "UserService"class= "Com.foo.SimpleUserService">              < Propertyname= "Userpreferences"ref= "Userpreferences"/>      </Bean> 

In the XML configuration file, to create a proxy for a scope bean, simply insert a child element into the scope bean definition <aop:scoped-proxy/> (you may also need to include the Cglib library in the classpath so that the container can implement the class-based proxy ; You may also want to use an XSD-based configuration). The XML configuration above shows "How to Do" and now discusses "why." request session globalSession Why do you need this element in the scope of the bean definition, as well <aop:scoped-proxy/> ? Let <aop:scoped-proxy/> 's start with the XML configuration that removes the element:

<BeanID= "Userpreferences"class= "Com.foo.UserPreferences"Scope= "Session"/>  <BeanID= "Usermanager"class= "Com.foo.UserManager">     < Propertyname= "Userpreferences"ref= "Userpreferences"/> </Bean>

From the above configuration can be clearly seen Singleton bean  Usermanager was injected with a pointer to http  Session Scope Bean   a reference to userpreferences . singleton  Usermanager  bean is only instantiated once by the container, and its dependencies ( userpreferences   Bean) is injected only once. This means that Usermanager only theoretically operates on the same userpreferences object, which is the bean that was originally injected. and inject a http  the Session scope of the bean as a dependency is against our original intention. Because all we want is a Usermanager object, and when it goes into a http  Session life cycle, we want to use a http  The userpreferences object of the Session .

When an object of type is injected, the object implements the UserPreferences same public interface (that is, the UserPreferences instance) as the class. And no matter what scope mechanism we choose (HTTP request, and Session so on), the container will be smart enough to get to the 真正的 UserPreferences object, so we need to inject the object's proxy into the userManager bean, and userManager The bean does not realize that it holds a pointer UserPreferences to a reference. In this example, when UserManager an instance invokes a UserPreferences method that uses an object, the method that is actually called is the proxy object. The proxy object then gets the Session real object from HTTP UserPreferences and delegates the method call to the actual object that was fetched UserPreferences .

Custom scopes

Details Baidu, know that there is such a thing on the line

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.