March 14, 2022

Spring Bean Scopes

Using a Spring bean definition, Spring container not only instantiates a bean and wire its dependencies it also provides the scope of the objects created from a particular bean definition. There is inbuilt support for six spring bean scopes in Spring Framework. Out of these six bean scopes four are available only if you use a web-aware ApplicationContext. You can also create a custom scope.

Supported Spring bean scopes

  1. Singleton scope- Single object instance corresponding to a bean definition is created for each Spring IoC container. Singleton scope is a default bean scope.
  2. Prototype scope- New object instance is created every time bean is requested from the Spring container.
  3. Request scope- For each HTTP request new bean instance is created. This Spring bean scope is valid only in the context of a web-aware Spring ApplicationContext.
  4. Session scope- Single bean instance is scoped to the lifecycle of an HTTP Session. This scope is valid only in the context of a web-aware Spring ApplicationContext.
  5. Application scope- Scopes a single bean definition to the lifecycle of a ServletContext. This scope is valid only in the context of a web-aware Spring ApplicationContext.
  6. Websocket scope- Scopes a single bean definition to the lifecycle of a WebSocket. This scope is valid only in the context of a web-aware Spring ApplicationContext.

Singleton scope for spring bean

When you scope a bean as a singleton, the Spring container creates exactly one instance of the object defined by that bean definition. All requests for beans with an ID matching that bean definition result in that one specific bean instance being returned by the Spring container.

The singleton scope is the default scope in Spring, if you don't provide bean scope in the bean definition, bean is created with scope as singleton.

Note that the scope of the Spring singleton is per-container and per-bean. Though the Spring container creates one and only one instance of the class defined by that bean definition but you can still create other objects of that bean which are not managed by the Spring container.

XML configuration example of a singleton scoped bean-

<bean id="abcBean" class="com.knpcode.BeanService" scope="singleton"/>

It is equivalent to the following definition as singleton scope is the default scope-

<bean id="abcBean" class="com.knpcode.BeanService"/>

Defining singleton scoped bean using @Scope annotation-

@Service
@Scope("singleton")
public class BeanService{
 ...
 ...
}

Spring bean prototype scope

When a bean is scoped as prototype, new bean instance is created every time a request for that specific bean is made.

Spring does not manage the complete lifecycle of a prototype bean. For prototype scoped beans initialization lifecycle callback methods are called but the configured destruction lifecycle callbacks are not called. The client code is responsible for cleaning up prototype-scoped objects and releasing resources that the prototype beans hold.

XML configuration example of a prototype scoped bean-

<bean id="abcBean" class="com.knpcode.BeanService" scope="prototype"/>

Defining prototype scoped bean using annotation-

@Service
@Scope("prototype")
public class BeanService{
 ...
 ...
}

Request scope

For a request scoped bean the Spring container creates a new instance of the bean for each and every HTTP request. These instances are particular to an individual request and the instance is destroyed when the request completes processing.

XML configuration example of a request scoped bean-

<bean id="abcBean" class="com.knpcode.BeanService" scope="request"/>

If you want to use annotation then @RequestScope annotation can be used to assign a component to the request scope or you can use @Scope(WebApplicationContext.SCOPE_REQUEST).

@RequestScope
@Service
public class BeanService{
 ...
 ...
}

Session scope

For a session scoped bean the Spring container creates a new instance of the bean for the lifetime of a single HTTP Session. That means bean is scoped at the HTTP Session level and it is discarded when that particular HTTP Session is discarded.

XML configuration example of a session scoped bean-

<bean id="abcBean" class="com.knpcode.BeanService" scope="session"/>

If you want to use annotation then @SessionScope annotation can be used to assign a component to the request scope or you can use @Scope(WebApplicationContext.SCOPE_SESSION).

@SessionScope
@Service
public class BeanService{
 ...
 ...
}

Application scope

For an application scoped bean the Spring container creates a new instance of the bean once for the entire web application. That means bean is scoped at the ServletContext level and stored as a regular ServletContext attribute.

XML configuration example of an application scoped bean-

<bean id="abcBean" class="com.knpcode.BeanService" scope="application"/>

If you want to use annotation then @ApplicationScope annotation can be used to assign a component to the request scope or you can use @Scope(WebApplicationContext.SCOPE_APPLICATION).

@ApplicationScope
@Service
public class BeanService{
 ...
 ...
}

WebSocket bean scope in Spring

The Spring Framework provides a WebSocket API that you can use to write client- and server-side applications that handle WebSocket messages. WebSocket scoped beans are typically singletons and live longer than any individual WebSocket session. Therefore, you need to use a scope proxy mode for WebSocket-scoped beans.

@Component
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {
 ...
 ...
}

For the Spring bean scopes request, session, application, and websocket you need to register the org.springframework.web.context.request.RequestContextListener. For Servlet 3.0+, this can be done programmatically by using the WebApplicationInitializer interface. If you use a Servlet 2.5 web container, then this registration has to be done explicitly by adding the following declaration to your web application’s web.xml file-

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

That's all for the topic Spring Bean Scopes. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment