☕ Spring Bean Scopes – Explained Like You’re Shopping Online ๐
In one of my interviews, I was asked a simple question: "What are the scopes in Spring and when will you use them?" I thought I knew it... until the interviewer confused me so much that I started mixing prototype with singleton and session with application ๐คฏ. So here’s my real-time, e-commerce-style explanation of Spring bean scopes — with code, diagrams, and some fun analogies!
1️⃣ Singleton Scope – ๐ฆ The Universal Product
Definition: Spring creates only one instance of the bean for the entire application context. Every @Autowired
injection gets the same object.
๐ E-Commerce Example:
Think of Amazon's Shipping Service. Every order uses the same logic, the same configuration — no need to create a new object for each request.
@Component
@Scope("singleton") // Default one , So you don't want to mention explicitly
public class ShippingService {
private String shippingProvider = "BlueDart";
public void shipOrder(String orderId) {
System.out.println("Shipping " + orderId + " via " + shippingProvider);
}
}
๐ Diagram:
+--------------------+ | Singleton Bean |---- used by ----> Request #1 | (One per Context) |---- used by ----> Request #2 | |---- used by ----> Request #3 +--------------------+
Wrong alternative for Singleton: Using Application scope in a microservice — works, but overkill unless you want to share between multiple servlet contexts.
2️⃣ Prototype Scope – ☕ Freshly Brewed Per Order
Definition: Spring creates a new instance every time you call getBean()
or inject it.
๐ E-Commerce Example:
Think of a Starbucks Custom Coffee. Every customer gets a fresh cup, tailored to their order — not poured from yesterday’s pot!
@Component
@Scope("prototype")
public class InvoiceGenerator {
public InvoiceGenerator() {
System.out.println("New InvoiceGenerator instance created");
}
public void generate(String orderId) {
System.out.println("Generating invoice for " + orderId);
}
}
๐ Diagram:
Request #1 ---> [InvoiceGenerator#1] Request #2 ---> [InvoiceGenerator#2] Request #3 ---> [InvoiceGenerator#3]
๐ก When to use:
- When the bean holds state specific to a single operation/request.
- When you can’t (or shouldn’t) share instances.
Wrong alternative for Prototype: Using Request scope in non-web background tasks — request scope won’t even work without an HTTP request context.
3️⃣ Request Scope – ๐ฎ Per Customer Request (Web Only)
Definition: Spring creates one bean instance per HTTP request and discards it after the response is sent.
๐ E-Commerce Example:
Imagine an Order Summary Page. The data lives only for that single page request. After the page is loaded, it’s gone.
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CartSummary {
private List items = new ArrayList<>();
public void addItem(String item) { items.add(item); }
public List getItems() { return items; }
}
๐ Diagram:
HTTP Request 1 ---> [CartSummary#1] HTTP Request 2 ---> [CartSummary#2] HTTP Request 3 ---> [CartSummary#3]
Wrong alternative for Request scope: Using Prototype in a web request when you need Spring to automatically tie the lifecycle to HTTP — you’ll have to manually manage destruction.
4️⃣ Session Scope – ๐️ Shopper’s Personal Cart
Definition: One bean instance per HTTP session. Multiple requests from the same user share it until session expires.
๐ E-Commerce Example:
The user’s shopping cart — same cart for all requests until they log out or session expires.
@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ShoppingCart {
private List products = new ArrayList<>();
public void addProduct(String product) { products.add(product); }
public List getProducts() { return products; }
}
๐ Diagram:
Session #1 (User A) ---> [CartA] Session #2 (User B) ---> [CartB]
Wrong alternative for Session scope: Using Singleton to store per-user data — BIG security risk, as user data can leak between sessions.
5️⃣ Application Scope – ๐ Shared Across the Whole Application
Definition: One bean instance for the entire ServletContext (shared across all requests and sessions within the same web app).
๐ E-Commerce Example:
Think of site-wide configuration — e.g., current promotional banner data loaded at startup and shared with all users.
@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION)
public class PromotionService {
private String currentPromo = "Buy 1 Get 1 Free!";
public String getPromo() { return currentPromo; }
}
๐ Diagram:
[PromotionService] ---> used by ---> Request #1 ---> used by ---> Request #2 ---> used by ---> Request #3
Wrong alternative for Application scope: Using Singleton when you actually want to share data across multiple servlet contexts in the same container (Singleton is per Spring context, not per servlet context).
๐ง Prototype vs Request – Are They the Same?
No. Both give you a new object per request in practice, but:
- Prototype → works in any environment (even without HTTP), you control its lifecycle.
- Request → tied to HTTP request lifecycle, auto-destroyed after response.
๐ฌ Wrapping Up
Understanding Spring scopes isn’t just about knowing definitions — it’s about knowing when to use which without accidentally shooting yourself in the foot ๐ฃ๐ซ.
"One day, everything will make sense — until then, keep coding, keep breaking, keep fixing." ๐
Have you ever messed up a scope in a hilarious or painful way? Share your story below — I promise, I’ve done worse! ๐
Comments
Post a Comment