Know the east wind surface, full of colors always spring.

An overview of the

In the Spring framework, we can create beans in the six built-in Spring Bean scopes, as well as define bean scopes. Of these six scopes, four are only available when using web-enabled applicationContext. Singleton and Prototype scopes can be used with any type of IOC container.

Spring Bean scope type

In Spring, you can use the @scope annotation in Spring to define the Scope of a bean. Below we have listed the six built-in bean scopes used in the context of a Spring application. These same scopes also apply to the Spring Boot Bean scope.

SCOPE describe
singleton spring IoCThe container has abeanObject instance.
prototype As opposed to singletons, each requestbean“, it creates a new instance.
request inHTTPRequest (Request), a single instance is created and used. Only applicable towebIn the environmentSpring ApplicationContextThe effective.
session inHTTPSession (Session), a single instance is created and used. Only applicable towebIn the environmentSpring ApplicationContextThe effective.
application Will be inServletContextCreate and use a single instance in the full life cycle of Only applicable towebIn the environmentSpring ApplicationContextThe effective.
websocket During the full life of a WebSocket, a single instance is created and used. Only applicable towebIn the environmentSpring ApplicationContextThe effective.

Singleton scope

Singleton is the default scope for beans in the Spring container. It tells the container to create and manage only one instance of the bean class. The single instance is stored in the cache of such a singleton bean, and all subsequent requests and references to the named bean return an instance of the cache.

Examples of singleton scoped beans with Java configuration:

@Component
@Scope("singleton")  // Can be omitted, default is singleton
public class BeanClass {}Copy the code

Example of a singleton scoped bean configured with XML:

<! -- Singleton can be omitted -->
<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="singleton" />
//or
<bean id="beanId" class="cn.howtodoinjava.BeanClass" />
Copy the code

Prototype scope

Each time an application requests a Bean, the stereotype scope creates a new instance of the Bean.

You should know that the destruction bean lifecycle method does not call the prototype scoped bean, only the initialization callback method. Therefore, as the developer, you are responsible for cleaning up the prototype-scoped bean instances and all the resources contained therein.

Example Java configuration of the prototype bean scope:

@Component
@Scope("prototype")
public class BeanClass {}Copy the code

Sample XML configuration of the prototype bean scope:

<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="prototype" />
Copy the code

In general, you should use stereotype scope for all stateful beans and singleton scope for stateless beans.

To use beans in the request, session, application, and WebSocket scope, you need to register RequestContextListener or RequestContextFilter.

The request scope

In the request scope, the container creates a new instance for each HTTP request. Therefore, if the server is currently processing 50 requests, the container can have up to 50 individual instances of the bean class. Any state change to one instance is not visible to the others. Once the request completes, these instances are destroyed.

Request Example Java configuration of the request bean scope:

@Component
@Scope("request")
public class BeanClass {}//or

@Component
@RequestScope
public class BeanClass {}Copy the code

Example of an XML configuration for the request bean scope:

<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="request" />
Copy the code

Session scope

In session scope, the container creates a new instance for each HTTP session. Therefore, if the server has 20 active sessions, the container can have up to 20 individual instances of bean classes. All HTTP requests within the lifetime of a single session can access the same single bean instance within the scope of that session.

Any state change to one instance is not visible to the other instances within the scope of the session. These instances are destroyed once the session is destroyed/terminated on the server.

Example Java configuration of the scope of the Session request bean:

@Component
@Scope("session")
public class BeanClass {}//or

@Component
@SessionScope
public class BeanClass {}Copy the code

Example OF an XML configuration for the scope of the Session request bean:

<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="session" />

Copy the code

Application scope

Within the application scope, the container creates an instance for each Web application run time. It is almost like a singleton scope, with two differences. That is:

  1. Application scopebeanIs eachServletContextSingleton object, while singleton scopebeanIs eachApplicationContextThe singleton object of. Note that a single application may have multiple application contexts.
  2. Application scopebeanAs aServletContextProperty visible.

Example Java configuration for the Application Bean scope:

@Component
@Scope("application")
public class BeanClass {}//or

@Component
@ApplicationScope
public class BeanClass {}Copy the code

Example XML configuration for the Application Bean scope:

<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="application" />
Copy the code

Websocket scope

The WebSocket protocol supports bidirectional communication between the client and the remote host, and the remote host chooses to communicate with the client. The WebSocket protocol provides a single TCP connection for communication in both directions. This is especially useful for multi-user applications with synchronous editing and multi-user games.

In this type of Web application, HTTP is used only for the initial handshake. If the server agrees, the server can respond with HTTP status 101 (switching protocol). If the handshake succeeds, the TCP socket remains open and both the client and server can use it to send messages to each other.

Examples of Java configuration for the WebSocket bean scope:

@Component
@Scope("websocket")
public class BeanClass {}Copy the code

Examples of XML configuration for the WebSocket bean scope:

<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="websocket" />
Copy the code

Note that webSocket-scoped beans are typically singletons and live longer than any individual WebSocket session.

Custom thread scope

Spring also provides non-default thread scope using the class SimpleThreadScope. To use this scope, you must register it with the container using the CustomScopeConfigurer class.

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="thread">
                <bean class="org.springframework.context.support.SimpleThreadScope"/>
            </entry>
        </map>
    </property>
</bean>
Copy the code

Each request to the bean will return the same instance in the same thread.

Example Java configuration for thread bean scope:

@Component
@Scope("thread")
public class BeanClass {}Copy the code

Example XML configuration for thread bean scope:

<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="thread" />
Copy the code

conclusion

The Spring Framework provides six Spring bean scopes, with instances within each scope having a different lifecycle span. As developers, we must choose the scope of any container-managed beans wisely. Similarly, we must make informed decisions when beans with different scopes refer to each other.

Keep all the information given above in mind to answer any spring Bean scoped interview questions.

Spring 5 — Bean scopes