Blog Spring Boot

Understanding Spring Boot Bean Scopes: A Comprehensive Guide with Examples

Spring Boot, a powerful extension of the Spring framework, simplifies the development of new Spring applications through convention over configuration. One of the fundamental concepts in Spring and Spring Boot is the concept of bean scopes, which determine the lifecycle and visibility of beans managed by the Spring IoC (Inversion of Control) container. This guide will explore the different bean scopes available in Spring Boot and provide examples to illustrate their use in various scenarios.

Singleton Scope

The singleton scope is the default scope in Spring Boot. It ensures that only one instance of a bean is created and maintained in the entire container. This is particularly useful for beans that are stateless or where a shared instance can be used without side effects.

Example:

import org.springframework.stereotype.Component;

@Component // By default, beans are singleton scope
public class SingletonService {
    public void serviceMethod() {
        System.out.println("Singleton instance: " + this.hashCode());
    }
}

Prototype Scope

In the prototype scope, each request for a bean results in the creation of a new bean instance. This is useful when you need separate instances to avoid shared state between operations.

Example:

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class PrototypeService {
    public void serviceMethod() {
        System.out.println("Prototype instance: " + this.hashCode());
    }
}

Request Scope

Request scope is valid in the context of a web-aware Spring application. A bean with request scope is created once per HTTP request.

Example:

import org.springframework.web.context.annotation.RequestScope;
import org.springframework.stereotype.Component;

@Component
@RequestScope
public class RequestScopedBean {
    public void serviceMethod() {
        System.out.println("Request Scoped instance: " + this.hashCode());
    }
}

Session Scope

A session-scoped bean is created once per HTTP session. This scope is ideal for storing user session data.

Example:

import org.springframework.web.context.annotation.SessionScope;
import org.springframework.stereotype.Component;

@Component
@SessionScope
public class SessionScopedBean {
    public void serviceMethod() {
        System.out.println("Session Scoped instance: " + this.hashCode());
    }
}

Application Scope

Application scope shares a single instance across the entire servlet context. It is useful for sharing application-level data.

Example:

import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.stereotype.Component;

@Component
@ApplicationScope
public class ApplicationScopedBean {
    public void serviceMethod() {
        System.out.println("Application Scoped instance: " + this.hashCode());
    }
}

WebSocket Scope

WebSocket scope allows for the creation of a bean instance per WebSocket session. This is useful in applications that use WebSocket for communication.

Example:

This requires configuring WebSocket in your Spring Boot application, which is beyond the scope of this guide. However, defining a WebSocket-scoped bean follows a similar pattern, using the @WebSocketScope annotation (hypothetical, as Spring does not directly provide this scope; you’d typically manage WebSocket sessions at a higher level).

Conclusion

Understanding and utilizing the correct bean scope is crucial for the design and efficiency of your Spring Boot application. By selecting the appropriate scope, you can control the lifecycle of beans according to the specific needs of your application, ensuring optimal resource use and avoiding unwanted side effects from shared state. This guide has provided a foundation for understanding the different scopes available in Spring Boot and their practical applications.

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Design Pattern

Understanding the Builder Design Pattern in Java | Creational Design Patterns | CodeTechSummit

Overview The Builder design pattern is a creational pattern used to construct a complex object step by step. It separates
Blog Tech Toolkit

Base64 Decode

Base64 encoding is a technique used to encode binary data into ASCII characters, making it easier to transmit data over