123ArticleOnline Logo
Welcome to 123ArticleOnline.com!
ALL >> Computer-Programming >> View Article

Spring Framework Bean Scopes

By Author: Kapil Gupta
Total Articles: 1

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.

Originally published in Coding Bits

Total Views: 95Word Count: 996See All articles From Author

Computer Programming Articles

1. A Home Automation Architecture Based On Lora Technology
Author: Rhythm Kr Dasgupta

2. I 3 Vantaggi Principali Nell’adottare Una Soluzione Erp Per La Tua Azienda.
Author: gaster seo

3. Get Started With Machine Learning
Author: Sanjana

4. Design Contest
Author: Jose Fields

5. Importance Of Bonded Warehouse
Author: Brilliant infosys

6. What Is Quickbooks Integration?
Author: tds llp

7. 12 Flutter Apps You Never Knew Existed
Author: Deepak Malhan

8. Web Development
Author: Gexton App

9. Top Programming Languages In 2019
Author: infocampus

10. Graphic Designing In Karachi
Author: James Noah

11. When To Use Java For Your Ui?
Author: infocampus

12. 10 Useful Unit And Integration Testing Apparatuses For Java Programmers
Author: infocampus

13. A Safety Guide For New Drone Users
Author: Marco

14. Crafting Your Own Mobile Application | Mobile App Development Austin
Author: Lisa

15. Best Java Frameworks That Tech Companies Really Use
Author: infocampus

Login To Account
Login Email:
Password:
Forgot Password?
New User?
Sign Up Newsletter
Email Address: