Spring series four: Bean Scopes Scope

Truthfulness east side, always colorful spring.

Here Insert Picture Description

Outline

In the Springframework, we can in six built-in spring beanto create a scope bean, you can define beanthe range. Of the six range, only in support of the use of Webthe applicationContexttime, four of which are available. singletonAnd a prototypescope can be used in any type of ioccontainer.

Spring Bean scope type

In Spring, you can use springthe @Scopeannotation defined beanscope. Below we have listed six in Springthe built-use application context in beanscope. These same scope also applies to the spring boot beanscope.

SCOPE description
singleton spring IoCThere is a container beanobject instance.
prototype In contrast to a single embodiment, each request bean, it creates a new instance.
request In the HTTPrequest ( Request) the complete life cycle, will create and use a single instance. It applies only to webthe environment Spring ApplicationContexteffectively.
session In the HTTPsession ( Session) the complete life cycle, will create and use a single instance. It applies only to webthe environment Spring ApplicationContexteffectively.
application In the ServletContextfull life cycle to create and use a single instance. It applies only to webthe environment Spring ApplicationContexteffectively.
websocket In the complete life cycle of WebSocket, create and use a single instance. It applies only to webthe environment Spring ApplicationContexteffectively.

Scope singleton

singletonIt is springa container default scope bean. It only tells the container to create and manage a beanclass instance. The single instance such single embodiment is stored in beanthe cache, and the names beanof all subsequent requests and return a reference example for the cache.

Using Javaa single embodiment scope configuration beanexample:

@Component
@Scope("singleton")  //可以省略,默认即是singleton
public class BeanClass {

}

Using XMLa single embodiment scope configuration beanexample:

<!-- 后面的singleton可以省略 -->
<bean id="beanId" class="cn.howtodoinjava.BeanClass" scope="singleton" />
//or
<bean id="beanId" class="cn.howtodoinjava.BeanClass" />

Prototype scope

Every application to Beanproceed with the request, prototype scope will create a new Beaninstance.

You should know that the destruction of beanlife cycle approach is not called prototype scope bean, just call initialization callback method. Therefore, as a developer, you are responsible for cleaning up the prototype scoped beaninstance, and all the resources it contains.

Prototype beanrange Javaconfiguration example:

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

Prototype beanrange XMLconfiguration example:

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

Generally, you should have for all states beanto use the prototype scope for stateless beansingleton range.

To request, session, application and websocketuse of the range bean, you need to register RequestContextListeneror RequestContextFilter.

request scope

In the request scope, for each container HTTPto create a new instance of the request. Thus, if the server 50 requests the current process, the container can have up to 50 beanseparate instances of the class. Any instance of a state change to the other instances are not visible. Upon completion of the request, these examples will be destroyed.

requestRequest beanrange Javaconfiguration example:

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

//or

@Component
@RequestScope
public class BeanClass {
}

requestRequest beanrange XMLconfiguration example:

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

session scope

In the session scope, the container for each HTTPcreate a new instance of the session. Thus, if the server has 20 active sessions, the container can have up to 20 beanseparate instances of the class. All within a single session lifecycle HTTPrequests access to the same single session within the scope of this beanexample.

In the scope of the session, an instance of any state changes to other examples are not visible. Once the session on the server is destroyed / end, these instances will be destroyed.

sessionRequest beanrange Javaconfiguration example:

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

//or

@Component
@SessionScope
public class BeanClass {
}

sessionRequest beanrange XMLconfiguration example:

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

application scope

Within the application range, for each container webto create an instance of the application runs. It is almost similar range of single embodiment, only two differences. which is:

  1. Application scope beaneach ServletContextsingleton object, singleton scope beaneach ApplicationContextsingleton object. Please note that a single application may have multiple application contexts.
  2. Application scope beanas the ServletContextvisible property.

application beanRange Javaconfiguration example:

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

//or

@Component
@ApplicationScope
public class BeanClass {
}

application beanRange XMLconfiguration example:

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

websocket Scope

WebSocketProtocol supports two-way communication, remote host selection and client communication between the client and the remote host. WebSocketProtocol provides a communication for the two separate directions of the TCPconnections. This is particularly useful for multi-user applications with synchronous editing and multi-user games.

In this type of Webapplication HTTPonly for the initial handshake. If the server agree, the server may HTTPrespond to a state 101 (exchange protocol). If the handshake is successful, the TCPsocket remains open, the client and server can use the socket to send messages to each other.

websocket beanRange Javaconfiguration example:

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

websocket beanRange XMLconfiguration example:

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

Note that, websocketin the range beantypically single embodiment, and the ratio of any single WebSocketlonger life conversation.

Custom thread scope

SpringAlso uses the class SimpleThreadScopeprovides a non-default thread scope. To use this scope, you must use the CustomScopeConfigurerclass to register it to the container.

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

On beaneach request will be returned in the same instance of the same thread.

Thread beanrange of Javaconfiguration examples:

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

Thread beanrange of xmlconfiguration examples:

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

to sum up

Spring frameworkIt provides six Spring beanscopes, each instance has a different role within the life cycle span. As developers, we must wisely choose any container management beanrange. Similarly, when a different scope beanwhen referencing each other, we need to make an informed decision.

Keep in mind that all the information given above to answer any spring beaninterview question scope.


Here Insert Picture Description

??? attention to micro-channel public number java dry
from time to time information sharing Dry

Original link: the Spring 5 - Bean Scopes

Published 112 original articles · won praise 90 · Views 350,000 +

Guess you like

Origin blog.csdn.net/dandandeshangni/article/details/102658321