(Reference: Spring Docs - Bean Scopes)
πΉ What is a Bean Scope?
π‘ Bean Scope determines how long a bean lives and how many instances exist in the application.
π‘ Spring provides different scopes to manage beans depending on the use case.
π Types of Bean Scopes in Spring
π₯ Spring defines several bean scopes, divided into two categories:
- Singleton & Prototype β Standard scopes (used in ANY Spring app).
- Request, Session, Application, WebSocket β Web-specific scopes.
1οΈβ£ Singleton Scope (Default)
β
Only ONE instance exists for the entire application context.
β
Same instance is returned every time the bean is requested.
β
Best for stateless, reusable components (e.g., Service classes).
π Example:
import org.springframework.stereotype.Component;
@Component
public class PirateCaptain {
public PirateCaptain() {
System.out.println("π΄ββ οΈ Singleton Pirate Captain Created!");
}
}
π₯ Spring ensures only ONE PirateCaptain
instance exists!
2οΈβ£ Prototype Scope
β
A NEW instance is created every time the bean is requested.
β
Used for stateful objects that require separate instances.
β
Good for expensive objects that should NOT be shared.
π Example:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class TreasureMap {
public TreasureMap() {
System.out.println("πΊοΈ New Treasure Map Created!");
}
}
π₯ Each time you getBean(TreasureMap.class)
, a new instance is returned!
3οΈβ£ Request Scope (For Web Applications)
β
One instance per HTTP request (lives as long as the request).
β
Useful for objects needed only during request processing.
π Example:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("request")
public class ShipLog {
public ShipLog() {
System.out.println("π New Ship Log Created for Request!");
}
}
π₯ Every new HTTP request gets a new ShipLog
instance!
4οΈβ£ Session Scope (For Web Applications)
β
One instance per user session (persists across multiple requests).
β
Useful for session-based user data.
π Example:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("session")
public class PirateSession {
public PirateSession() {
System.out.println("π΄ββ οΈ New Pirate Session Created!");
}
}
π₯ Every user gets their own PirateSession
bean across multiple requests.
5οΈβ£ Application Scope (For Web Applications)
β
One instance for the ENTIRE application (shared across all requests & users).
β
Useful for storing global application data.
π Example:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("application")
public class GlobalPirateRules {
public GlobalPirateRules() {
System.out.println("π Global Pirate Rules Initialized!");
}
}
π₯ The same instance is shared across all users and requests.
π Hands-On Project: Exploring Bean Scopes
π‘ Letβs create a simple Spring Boot app to experiment with different bean scopes!
Step 1: Create a Spring Boot Project
1οΈβ£ Go to Spring Initializr
2οΈβ£ Select:
- Spring Boot Version: Latest stable
- Dependencies: Spring Web
- Packaging: Jar 3οΈβ£ Click Generate and extract the zip file.
Step 2: Create Beans with Different Scopes
π Create a Singleton Bean:
import org.springframework.stereotype.Component;
@Component
public class SingletonPirate {
public SingletonPirate() {
System.out.println("π΄ββ οΈ Singleton Pirate Created!");
}
}
π Create a Prototype Bean:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class PrototypeTreasure {
public PrototypeTreasure() {
System.out.println("π New Prototype Treasure Created!");
}
}
Step 3: Inject and Test Scopes in a REST Controller
π Create a ScopeController
to observe bean behavior:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/scopes")
public class ScopeController {
private final SingletonPirate singletonPirate;
private final PrototypeTreasure prototypeTreasure;
public ScopeController(SingletonPirate singletonPirate, PrototypeTreasure prototypeTreasure) {
this.singletonPirate = singletonPirate;
this.prototypeTreasure = prototypeTreasure;
}
@GetMapping("/singleton")
public String getSingleton() {
return "π΄ββ οΈ Singleton Pirate Hash: " + singletonPirate.hashCode();
}
@GetMapping("/prototype")
public String getPrototype() {
return "π Prototype Treasure Hash: " + prototypeTreasure.hashCode();
}
}
Step 4: Run the Application & Test
π‘ Run the app using:
mvn spring-boot:run
or
./mvnw spring-boot:run
π Open browser & test the endpoints:
1οΈβ£ Call Singleton Endpoint:
http://localhost:8080/scopes/singleton
-
Response:
π΄ββ οΈ Singleton Pirate Hash: 12345678
Same value every time!
2οΈβ£ Call Prototype Endpoint Multiple Times:
http://localhost:8080/scopes/prototype
-
Response:
π Prototype Treasure Hash: 87654321
Different value each time!
π₯ Boom! You just witnessed Spring Bean Scopes in action!
π Summary of Step 4
β
Singleton (Default): One instance per application.
β
Prototype: A new instance every time.
β
Request: One instance per HTTP request (Web apps only).
β
Session: One instance per user session (Web apps only).
β
Application: One instance for the entire app (Web apps only).
π Topics Covered in This Section
π Spring Bean Scopes (βοΈ Covered)
- Singleton (Default scope, one instance per container).
- Prototype (New instance every time).
- Request Scope (New instance per HTTP request).
- Session Scope (New instance per user session).
- Application Scope (Shared instance for the entire application).
π οΈ Spring Boot & Scopes (βοΈ Covered)
- Using @scope annotation.
- How singleton vs. prototype works in dependency injection.
- Scope behavior in REST APIs.
π₯ Key Takeaways You Need to Remember:
β
Singleton is the default scope.
β
Prototype creates a new bean instance every time.
β
Web scopes (Request, Session, Application) require Spring Web.
β
Use @scope("prototype") carefully when injecting into Singleton beans (can cause issues).
Top comments (0)