Spring-bean scope

1. Spring Framework supports five scopes

 

1. singleton: a bean definition corresponds to an object instance (spring container default scope)

2. prototype: a bean definition corresponds to multiple object instances (the prototype scope should be used for all stateful beans, and the singleton scope should be used for stateless beans. Dao will not be configured as a prototype and should be stateless singleton

 

3. 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 according to a bean definition. This scope is only valid in the case of a web-based spring applicationcontext.

4. Session: In an http session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based spring applicationcontext

5, global session: In a global http session, a bean definition corresponds to an instance 

 

Second, the scope of web use

1. Request scope: valid within the current http request, when the request ends, the bean instance in the request scope will be destroyed

2. Session scope: valid within the current http Session

3. The global session scope: only meaningful in portlet-based web applications

 

3. Scoped beans and dependencies

1. It is good to be able to define beans in the scope of HTTP request or Session (or even custom), but the Spring IoC container is responsible for the instantiation of collaborators (or dependencies) in addition to managing the instantiation of objects (beans). If you intend to inject an Http request scoped bean into another bean, then you need to inject an AOP proxy in place of the injected scoped bean. That is to say, you need to inject a proxy object, which has the same public interface as the proxy object, and the container can be smart enough to obtain the real target object from the relevant scope (such as an HTTP request), and put The method call is delegated to the actual object

 

2. In the xml configuration file, create a proxy for a scoped bean

     

<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-3.0.xsd

 

  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

 

<aop:scoped-proxy/>

 

 

3. Reference documents

http://www.xuehuile.com/blog/14f393edfeb24c259caaf5cf762ceb1d.html

      http://blog.arganzheng.me/posts/spring-bean-scopes.html

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326709927&siteId=291194637