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

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too 🤔. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” 😅 Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model 👩‍💻 Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections 👉 Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside 🚪 ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

💡 Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😵‍💫 “Why is Redis cache not working?” 🤯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🤷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } 🕵️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: 🛂 Watchman = Spring Proxy 🏠 Your apartment = Your service class 🚪 Your room = A method inside that class 🏃 Scenario 1: Outsider Visits Your friend from outside...

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