In the Spring Framework, every bean definition implicitly or explicitly includes a 'scope' attribute.In Java configuration, it is specified using the
@Scope annotation, and in XML it is the
scope attribute of the
<bean> tag.
The 'scope' attribute is an identifier string that associates a bean with an instance of the class
org.springframework.beans.factory.config.Scope.Scope is an implementation of the "strategy" pattern for bean factories, a recipe to create business objects.
In the simplest Spring application, there are always two scopes:
•
singleton – the object is created once and reused in subsequent
injections. It is useful for most cases: various services, stateless objects,
immutable objects. It is important to note that this is not a singleton class: declaring two beans of the same class results in two instances.
This is the default scope.
•
prototype – each injection results in the creation of a new object by the bean factory. This is necessary for mutable beans with state.
Spring Web adds four additional scopes, which makes a bean behave like a singleton within the confines of handling a single network request (
request), a client session (
session), a servlet context (
application) and a websocket session (
websocket).
Developers can add their own scopes. An example implementation can be found in the Spring source itself:
SimpleThreadScope, which makes the bean
thread-local. To use it, as well as custom scopes, you must first register it in the
BeanFactory.