Module 4: Spring Bean Scopes (How many Objects?)
📚 Module 4: Spring Bean Scopes
Focus: Moving from “Always New” to “Shared Objects.”
In normal Java, when you call new, you get a fresh object. In Spring, the Butler (Container) usually gives everyone the Same Object to save memory. This is called a Singleton.
🏗️ Step 1: Singleton Scope (The “Shared Office”)
By default, every Bean in Spring is a Singleton.
🧩 The Analogy: The Coffee Pot
Imagine an office with 10 employees. Instead of every employee having their own personal coffee machine on their desk, there is One Giant Coffee Pot in the breakroom.
- Everyone shares the same pot.
- If one person puts sugar in the pot, everyone else tastes the sugar.
In Code: Spring creates the object once and “Injects” it into every class that asks for it.
🏗️ Step 2: Prototype Scope (The “Personal Lunch”)
Sometimes, you do want a fresh object every time.
🧩 The Analogy: The Subway Sandwich
- When you order a sandwich, you don’t want to share it with the person behind you.
- Every time you ask for a Bean, the Butler builds a Brand New one just for you.
🏗️ Step 3: Web Scopes (The “Hotel Room”)
When building web apps, we have even more specialized scopes:
- Request Scope: The object only lives for as long as one “Click” (One HTTP Request).
- Session Scope: The object lives for as long as the user stays logged in.
🥅 Module 4 Review
- Scope: How long a Bean lives and who shares it.
- Singleton (Default): One shared object for the entire app.
- Prototype: A new object every time someone asks.
- Request/Session: Objects tied to a specific user’s web visit.
Riverside. Riverside.