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...

๐ŸŒŸ My Journey – From Zero to Senior Java Tech Lead ๐ŸŒŸ

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. ๐Ÿ’ฏ Sounds crazy? Let me take you back. ๐Ÿ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . ๐Ÿงช Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...

๐ŸŽข 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...