View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Spring Bean Scopes: Singleton & Prototype Scopes

By Rohan Vats

Updated on Jul 03, 2023 | 7 min read | 6.6k views

Share:

Spring framework is one of the best open-source frameworks for the top-rated programming platform Java and provides massive infrastructure support for easily and quickly developing applications. It was written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Application of Spring framework includes its benefits of modular framework, Integration with existing frameworks, testability on fake or development data, well-designed web MVC framework, Central exception handling, Unbelievably lightweight, and onboard transaction management. 

For any object-oriented programming language, one needs to design objects that form your application development’s backbone, and spring manages it using the spring IOC container called beans. A bean is an object managed entirely by the IOC container provided by spring. 

Check out our free courses to get an edge over the competition

The definition of the bean contains three essential factors which come under configuration metadata and includes:

  1. How to create a bean.
  2. The details of the bean’s life cycle.
  3. All the dependencies.

Scopes can be declared while defining a bean and is usually set using scope attribute to one of the five types possible. These five types of scope attribute include the following types:

  1. Singleton: The scope is used to define the scope definition to a single instance every Spring IOC container. This is the default definition of any scope.
  2. Prototype: In some cases, if you want to produce a new bean instance every time needed, it is better to declare the bean’s scope attribute as a prototype.
  3. Request: If you are working on a web-aware spring application, the request scopes the bean definition to an HTTP request.
  4. Session: If you are working on a web-aware spring application context, the session scopes the bean definition to an HTTP session.
  5. Global Session: Global Session scopes a bean definition to a global HTTP session and is only proven in a web-aware Spring Application.

Read: Top Spring Boot Features

Initial Web Configuration:

Configuring bean scopes in Spring application can be done through XML or annotations. The Spring Bean Scopes attribute in XML or the @Scope annotation can be used to define the scope of a bean.

The Singleton Scope

The scope is used to define the scope definition to a single instance of every IOC container in the Spring. This is the default definition of any scope. Now, that single instance is created and pushed in a cache of these singleton beans, and then that cached object can be returned using regular requests. 

As we know, the default declaration for the scope is set to singleton. Still, this code sample can be used to set the scope to the singleton.

Check out upGrad’s Advanced Certification in Cloud Computing 

Enrol in Online Software Development Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Singleton Beans with Prototype-Bean Dependencies:

Handling Singleton beans that have dependencies on Prototype beans can be challenging. By default, the Singleton bean will receive the same instance of the Prototype bean for each request, which may lead to unintended consequences. To manage this scenario, a scoped proxy can be used to ensure that the Singleton bean always receives a new instance of the Prototype bean.

The Prototype Scope

Now, if you are dealing with multiple instance requests for the object every time the user requests that specific bean, in this case, the Spring IoC container creates a new bean instance for the object every time a new request is made. One can use the prototype scope for all state-full beans.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Request Scope: Code for the request scope:

<bean id=”loginAction” class=”com.foo.LoginAction” scope=”request”/>

Using the loginAction bean definition, the spring container can create a completely new and specific instance for the LoginAction bean for every HTTP request. The change in the specific instance’s main interior state would not affect other instances because these changes created by that same loginAction bean definition would register no changes in the state and are specific to that individual request.

Check out upGrad’s Advanced Certification in Cyber Security

Session scope:

Code for Session Scope:

<bean id=”userPreferences” class=”com.foo.UserPreferences” scope=”session”/>

Using the session scope, the spring container can create a very new UserPreferences instance of a bean using the user preferences bean definition for a complete HTTP session. The change in the specific instance’s main internal state would not affect other instances because these changes created from the same user preferences bean definition would register no changes in the state and are specific to a specific HTTP session. 

Global Session Scope:

Code for the Global Session Scope:

<bean id=”userPreferences” class=”com.foo.UserPreferences” scope=”session”/>

It is mostly similar to the original session scope and only applies to a limited range of portlet based website applications. All these beans, which are defined at the global session scope, are scoped to the end of life for the global portlet Session.

Also Read: Spring Boot Topics & Projects

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Scoped Beans as Dependencies:

Spring allows the injection of scoped beans as dependencies in other beans. This enables the utilization of appropriate spring scopes for each dependency, ensuring correct behaviour and lifecycle management.

Application Scope:

Beans with the Application scope exist for the entire lifespan of the application. A single instance of the bean is shared across all users. This scope is suitable for maintaining global application settings and shared resources.

WebSocket Scope:

Introduced in Spring 4.2, the WebSocket scope provides a dedicated bean instance for each WebSocket session. This allows each WebSocket session to have its instance of the bean.

Custom Scopes:

In addition to the built-in scopes, Spring provides the flexibility to create custom scopes tailored to specific requirements. A custom scope involves implementing the Scope interface and defining scoped beans’ instantiation and destruction behaviour.

Creating Your Own Custom Scope:

Once a custom scope is implemented, it can be registered with the Spring application context. This allows using the custom scope in bean definitions using the @Scope annotation or the scope attribute in XML.

Conclusion

Hence, the scope can be declared in various types and disciplines with a limited singleton scope to a global session scope. This helps you to access web applications and is an integral part of the spring bean framework.

Companies are looking for new and innovative technologies to work on, and MongoDB is one of them. These new-age skills are very useful to thrive in a competitive environment such as software development, where priorities change every time a new technology is evolved. 

We at upgrad are here to help you achieve that potential and develop your skills into assets for future companies and organizations by providing real-time inputs and extensive placement support. Make your future secure with us, and don’t let these challenges deprive you of your dreams.

If you’re interested to learn more about Spring Boot, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What makes Java so popular today?

2. Why is Spring named Spring?

3. What are other frameworks present in Java?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program