Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconSpring Bean Scopes: Singleton & Prototype Scopes [2024]

Spring Bean Scopes: Singleton & Prototype Scopes [2024]

Last updated:
9th Jun, 2023
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Spring Bean Scopes: Singleton & Prototype Scopes [2024]

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

Ads of upGrad blog

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”/>

Explore our Popular Software Engineering Courses

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

In-Demand Software Development Skills

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. 

Ads of upGrad blog

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.

Read our Popular Articles related to Software Development

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What makes Java so popular today?

Java is extremely popular among developers and programmers for several reasons. The best thing about Java is its platform-independent design. Java programs can be executed on different operating systems as long as the JRE, i.e., Java Runtime Environment, is installed on the system. Even though it has been around for almost 26 years now, Java keeps evolving with time and changing demands of the software industry. Besides, this programming language is considered more straightforward than many other programming languages, making it hugely popular with beginners. It can be used to develop different kinds of apps, starting from full-fledged software packages to mobile apps and web-based applications.

2Why is Spring named Spring?

Spring is the most widely employed framework for application development in Java enterprise edition (J2EE). It is a powerful but lightweight framework that offers features that can be used to develop any Java application. The name Spring was given to this framework to indicate a fresh start after the so-called winter of conventional J2EE. It was initially given the name Interface 21 to imply the 21st century and launched under the license of Apache 2.0. Today, Spring is extensively used in the development of Java applications. It is liked by programmers and developers mainly due to its simplicity, testability, and loose coupling features.

3What are other frameworks present in Java?

Java is one of the most popular, powerful, and versatile programming languages today. Java frameworks offer a base that enables developers to build software applications for specific platforms. So these frameworks essentially provide programmers with software and standards specific to the development and deployment of applications. There are more than 30 frameworks in Java; software developers use various Java frameworks today for application development. Some of the most popular ones are Spring, Play, Hibernate, Apache Struts, Dropwizard, Java Server Faces (JSF), Google Web Toolkit (GWT), Blade, Vaadin, and Grails. Out of all the Java frameworks, Spring is considered the most powerful and popular.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31584
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46947
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901333
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
52128
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909210
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34763
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902394
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26265
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4394
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon