• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Coding Bits

Free Java, Spring Resources

  • Spring

Spring5

Spring Bean Scopes

May 11, 2019 by admin Leave a Comment

Spring provides a powerful and flexible way to choose and control the scope of the objects created from a given bean definition.
There are total 6 scopes supported by Spring Framework. Out of the these 4 of them are available only if you use a web-aware
ApplicationContext

Scope Description Default
singleton Single bean instance will be createad per Spring IoC container. Yes
prototype Any number of instances can be created corresponding to the bean definition. No
request Single Bean Instance will be available for the lifecycle
of a single HTTP request.
No Only valid in the context of a web-aware Spring
ApplicationContext.
session Single Bean Instance will be available for the complete lifecycle
of an HTTP Session.
No Only valid in the context of a web-aware Spring
ApplicationContext.
application Single Bean Instance will be available for the lifecycle
of a ServletContext.
No Only valid in the context of a web-aware Spring
ApplicationContext.
websocket Single Bean Instance will be available for the lifecycle
of a WebSocket.
No Only valid in the context of a web-aware Spring
ApplicationContext.

Singleton scope

This is the default scope for all the beans in Spring unless you explicitly specify a different scope. Spring creates only a single shared instance for all the requests for a bean definition.

Spring creates and caches all such singleton scope beans and subsequent requests get fulfilled from the cache. Please note that concept of Spring Singleton beans is different from the Singleton pattern from the GoF(Gang of Four). In GoF Singleton the scope of the singleton object is one instance per ClassLoader, however in the spring it is one instance per IoC container and per bean.

This is how you define a bean with singleton scope using XML based configuration:


Prototype scope

With Prototype scope, a new instance is created using the bean definition every time there is a new request for a specific bean.

When to use Singleton scope and when to use Prototype bean scope
Always use Singleton scope for stateless beans and the prototype scope stateful beans.
For example: A DAO (Data access Object) typically will be configured as singleton because it does not hold any state.

The following example defines a bean as a prototype in XML:


Spring is not responsible for managing the complete lifecyle of prototype scoped objects as compared to other scopes. The Spring container is only responsible to create and configure the prototype object and then hands it over the requester. Hence only the initialization lifecycle callback methods are called on a prototype, destruction lifecycle callbacks are not called.

The requesting code is responsible to clean up the protype objects.

As pointed in the Bean Scopes table, request, session, application, and websocket scopes are only available if you use a web-aware Spring ApplicationContext implementation like XmlWebApplicationContext, otherwise you will get an error complaining about unknown bean scopes.

Request scope

In request scope, Spring container will create a new instance for each new HTTP request. Changes to the state of a particular instance of Request scoped object will not be visible to other instances of the same bean definition. Once request lifecycle is complete these request scoped objects will be discarded by Spring container.

The following example defines a bean as a Request Scope in XML:


The following example shows java based configuration on how to assign the request scope using @RequestScope annotation:

@RequestScope
@Component
public class RequestAction {
    // ...
}

Session scope

In Session scope, Spring container will create a new instance for each new HTTP Session. Changes to the state of a particular instance in one session will not be visible to other sessions. Once session terminates objects will be discarded by Spring container.

The following example defines a bean as a Request Scope in XML:


The following example shows java based configuration on how to assign the request scope using @SessionScope annotation:

@SessionScope
@Component
public class UserConfig {
    // ...
}

Application scope

When using Application scope, Spring container will create a single instance of a bean for entire web application context. The instance will be stored as ServletContext. It is like a Singleton per ServletContext instead of per ApplicationContext Once session terminates objects will be discarded by Spring container.

The following example defines a bean as an Application Scope in XML:


The following example shows java based configuration on how to assign the request scope using @SessionScope annotation:

@ApplicationScope
@Component
public class ApplicationPreferences {
    // ...
}

WebSocket scope

Websocket scoped beans are more like the singleton scoped beans and stay longer than the individual WebSocket session.

The following example defines a bean as a WebSocket Scope in XML:


The following example shows java based configuration on how to assign the request scope using @WebSocket annotation:

@WebSocket
@Component
public class MyBean {
    // ...
}

Custom Spring Beans Scope

The Spring bean scope mechanism is extensible. It allows defining custom scopes and redefining existing ones except from the singleton and prototype scopes.

Following example shows how to use the SimpleThreadScope.This is already included in Spring framework but not registered by default. To use this scope, We need to first register the scope with the container using the CustomScopeConfigurer class.


    
        
            
                
            
        
    

Since we have scoped the bean at Thread scope, same instance of bean will be returned for each request made by a single thread.

The following example defines a bean with thread Scope in XML:




The following example shows java based configuration on how to assign the request scope using @WebSocket annotation:

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

Summary

In this article we had an overview of all the possible Spring Bean Scopes. This is an important Spring interview question, one should be comfortable in choosing the correct scope for a particular requirement. Which Please leave your comments below in case you have any questions or you find any correction in above content.

More Resources available at :

Scope – Spring Docs
Spring Tutorials

Filed Under: Spring Tagged With: Spring, Spring Beans Scope, Spring5

Primary Sidebar

Categories

  • Daily Coding Problem
  • Design Patterns
  • Java
  • Spring

Tags

Spring Spring5 Spring Beans Scope

Copyright © 2019 · Coding Bits on Genesis Framework · WordPress · Log in