Skip to main content

๐Ÿ›’ Spring Bean Scopes – Explained with an E-Commerce Website

☕ 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

Popular posts from this blog

๐Ÿ” Is final Really Final in Java? The Truth May Surprise You ๐Ÿ˜ฒ

๐Ÿ’ฌ “When I was exploring what to do and what not to do in Java, one small keyword caught my eye — final . I thought it meant: locked, sealed, frozen — like my fridge when I forget to defrost it.”   But guess what? Java has its own meaning of final… and it’s not always what you expect! ๐Ÿ˜… Let’s break it down together — with code, questions, confusion, jokes, and everything in between. ๐ŸŽฏ The Confusing Case: You Said It's Final... Then It Changed?! ๐Ÿซ  final List<String> names = new ArrayList <>(); names.add( "Anand" ); names.add( "Rahul" ); System.out.println(names); // [Anand, Rahul] ๐Ÿคฏ Hold on... that’s final , right?! So how on earth is it still changing ? Time to dive deeper... ๐Ÿง  Why Is It Designed Like This? Here’s the key secret: In Java, final applies to the reference , not the object it points to . Let’s decode this like a spy mission ๐Ÿ•ต️‍♂️: Imagine This: final List<String> names = new ArrayList <>(); Be...

๐ŸŽข Java Loops: Fun, Fear, and ForEach() Fails

๐ŸŒ€ Oops, I Looped It Again! — The Ultimate Java Loop Guide You Won't Forget “I remember this question from one of my early interviews — I was just 2 years into Java and the interviewer asked, ‘Which loop do you prefer and why?’” At first, I thought, “Duh! for-each is cleaner.” But then he grilled me with cases where it fails. ๐Ÿ˜ต That led me to explore all loop types, their powers, and their pitfalls. Let’s deep-dive into every major Java loop with examples &  real-world guidance so you'll never forget again. ๐Ÿ” Loop Type #1: Classic For Loop — “The Old Reliable” ✅ When to Use: You need an index You want to iterate in reverse You want full control over loop mechanics ✅ Good Example: List<String> names = List.of("A", "B", "C"); for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } ๐Ÿ”ฅ Reverse + Removal Example: List<String> item...

๐Ÿงต Virtual Threads in Java — The Ultimate Guide with Diagrams, Code & Interview Qs!

๐Ÿš€ “How are Virtual Threads different from Thread Pools?” ๐Ÿ˜ต “Are they OS threads or JVM threads?” ๐Ÿ™ƒ “Should I still use CompletableFuture?” ๐Ÿคฏ “How do I even use them in real-time microservices?” ๐Ÿง  What are Virtual Threads? Virtual Threads (introduced in Java 21 as stable ๐ŸŽ‰) are lightweight threads managed by the JVM instead of the OS kernel. ๐Ÿ‘‰ They look like normal threads, but don’t hog OS resources like traditional threads. ๐Ÿง  What is the OS Kernel? ๐Ÿ›️ OS Kernel = The Brain of the Operating System It’s the core part of your OS (Windows, Linux, Mac) that: Manages memory ๐Ÿง  Schedules threads ๐Ÿ•’ Talks to hardware ๐Ÿ’ป Handles I/O operations ๐Ÿ“จ When you create a traditional thread in Java, the JVM asks the OS Kernel to create a real OS-level thread. ๐Ÿ–ผ️ Imagine This... ┌───────────────────────────┐ │ Your Java Application │ └────────────┬──────────────┘ │ ...