Demystifying Bean Scope in Spring: A Comprehensive Guide

Naveen Metta
5 min readNov 16, 2023

Introduction

In the vast landscape of Spring Framework, beans are the fundamental building blocks that drive the application’s functionality. Beans serve as objects managed by the Spring container, and their scopes define their lifecycle and visibility within the application context. In this article, we will embark on a journey to explore the concept of bean scope in Spring and its various types. We will dive deep into the details, accompanied by code examples to ensure a thorough understanding.

Understanding the Significance of Bean Scope

Before delving into the types of bean scope, it’s crucial to understand the significance of bean scope within the Spring Framework. In Spring, bean scope defines how long an instance of a bean should live and when it should be created. The scope of a bean impacts its lifecycle, thread-safety, and the visibility of the bean within the application context.

Spring offers a variety of bean scopes, each serving a specific purpose in different scenarios. By choosing the appropriate scope for your beans, you can control the behavior and performance of your application.

Types of Bean Scope in Spring

Spring provides several predefined bean scopes, each catering to specific use cases. Let’s explore these scopes in detail:

Singleton Scope:
The Singleton scope is the default scope for Spring beans. In this scope, a single instance of the bean is created for the entire application context. It ensures that all requests for the bean result in the same instance, promoting a shared and global state.

@Component
public class SingletonBean {
// Bean code here
}

In this example, any component that requests the SingletonBean will receive the same instance.

Prototype Scope:
The Prototype scope, on the other hand, creates a new instance of the bean every time it’s requested. This scope is useful when you need a unique instance for each client, ensuring that no shared state exists.

@Component
@Scope("prototype")
public class PrototypeBean {
// Bean code here
}

In the case of PrototypeBean, each request for the bean results in a new instance.

Request Scope:
Request scope is primarily designed for web applications using the Spring Framework. It ensures that a new instance of the bean is created for each HTTP request. This scope is valuable when you want to maintain state within a single HTTP request.

@Component
@Scope("request")
public class RequestScopedBean {
// Bean code here
}

Here, a new RequestScopedBean instance is created for every incoming HTTP request.

Session Scope:
Similar to Request scope, Session scope is tailored for web applications and guarantees a single instance of the bean per HTTP session. This is particularly useful when you need to maintain state throughout a user’s session.

@Component
@Scope("session")
public class SessionScopedBean {
// Bean code here
}

In this case, a single SessionScopedBean instance is created and shared throughout the user’s session.

Application Scope:
Application scope ensures that there is only one instance of the bean created for the entire web application. This scope is ideal for beans that need to maintain global state for the entire application.

@Component
@Scope("application")
public class ApplicationScopedBean {
// Bean code here
}

Here, a single ApplicationScopedBean instance is available for the entire application.

WebSocket Scope:
WebSocket scope is a specialized scope introduced in Spring 4.2 for WebSocket-based applications. It guarantees that a single instance of the bean is created for each WebSocket session, allowing for WebSocket-specific state management.

@Component
@Scope("websocket")
public class WebSocketScopedBean {
// Bean code here
}

WebSocket scope ensures that a new instance of WebSocketScopedBean is created for each WebSocket session.

Custom Scopes:
In addition to the built-in scopes, Spring allows you to define custom scopes to meet your specific requirements. This can be particularly useful when your application has unique use cases that don’t fit neatly into the predefined scope categories.

@Component
@Scope("customScope")
public class CustomScopedBean {
// Bean code here
}

To use custom scopes, you need to define them in your application context and configure the associated beans accordingly.

Choosing the Right Bean Scope

Selecting the appropriate bean scope is a critical decision in the development process. The choice of scope should align with your application’s requirements and the intended behavior of the beans. Let’s discuss some considerations to help you make an informed choice:

Singleton Scope:

Use when a single shared instance of a bean is required throughout the application.
Suitable for caching, service locators, and stateless beans.
Prototype Scope:

Use when a new instance of the bean is needed every time it’s requested.
Ideal for stateful beans or beans that manage temporary data.
Request and Session Scope:

Appropriate for web applications where you need to maintain state within an HTTP request or session.
Use Request scope for data that should be available during a single HTTP request.
Use Session scope for data that should persist throughout a user’s session.
Application Scope:

Suitable for maintaining global state within a web application.
Use with caution, as it may lead to tightly coupled components and potential concurrency issues.
WebSocket Scope:

Specifically designed for WebSocket-based applications.
Ideal for managing WebSocket session-specific state.
Custom Scopes:

Create custom scopes when none of the predefined scopes meet your specific requirements.
Carefully design and implement custom scopes to ensure they behave as expected.
Code Examples and Use Cases

To better understand the practical application of bean scopes, let’s explore a few use cases and code examples:

Scenario 1: Singleton Scope

Suppose you have a configuration bean that should be shared across the entire application. In this case, the Singleton scope is the right choice:

@Configuration
public class AppConfig {
// Configuration code here
}

Scenario 2: Prototype Scope

Consider a scenario where you need to create unique shopping cart instances for each user in an e-commerce application. The Prototype scope is the best fit:

@Component
@Scope("prototype")
public class ShoppingCart {
// Shopping cart code here
}

Scenario 3: Request Scope

In a web-based forum application, you might want to create a separate comment manager for each user’s HTTP request to handle real-time interactions. Request scope is the perfect choice:

@Component
@Scope("request")
public class CommentManager {
// Comment manager code here
}

Scenario 4: Session Scope

Suppose you are developing an online banking system where you need to manage user account information for the duration of their session. The Session scope is ideal:

@Component
@Scope("session")
public class UserAccountManager {
// User account manager code here
}

Scenario 5: Application Scope

For an e-commerce platform that needs to maintain a global product catalog across the entire application, the Application scope is a suitable choice:

@Component
@Scope("application")
public class ProductCatalog {
// Product catalog code here
}

By carefully selecting the appropriate scope for each bean, you can effectively manage state and resources within your Spring application.

Conclusion

In this comprehensive guide, we’ve explored the concept of bean scope in Spring and the various types available. Understanding and choosing the right scope for your beans is crucial for maintaining the desired behavior and performance of your application.

Singleton, Prototype, Request, Session, Application, WebSocket, and custom scopes all serve specific purposes and should be selected based on the requirements of your application. The choice of bean scope has a significant impact on the architecture and behavior of your application, so it’s important to make informed decisions.

By leveraging the power of Spring’s bean scopes and following best practices, you can build robust and efficient applications that meet the unique needs of your projects. Whether you’re developing web applications, microservices, or enterprise-level systems, mastering the nuances of bean scope will greatly enhance your Spring development skills. So go ahead, select the right scope, and let your Spring beans thrive!

--

--

Naveen Metta

I'm a Full Stack Developer with 2.5 years of experience. feel free to reach out for any help : mettanaveen701@gmail.com