π± Spring Bean Scopes¶
Spring beans donβt all live the same life. Some are long-term residents, others are quick visitors who grab a coffee and vanish βπͺ
Bean scope decides how long a bean lives and how many instances exist.
πΉ 1. Singleton (Default)¶
π One bean per Spring container
π§ Behavior¶
- Same instance reused everywhere
- Created once at startup
β Use When¶
- Stateless services
- Shared resources
β οΈ Caution¶
- Not thread-safe by default
πΉ 2. Prototype¶
π New bean every time it is requested
π§ Behavior¶
- Every
getBean()β new object - Spring does NOT manage full lifecycle (no destroy)
β Use When¶
- Stateful objects
- Temporary processing
πΉ 3. Request Scope (Web)¶
π One bean per HTTP request
π§ Behavior¶
- New instance for each request
- Destroyed after request ends
β Use When¶
- Request-specific data
- User input handling
πΉ 4. Session Scope (Web)¶
π One bean per HTTP session
π§ Behavior¶
- Shared across requests in same session
β Use When¶
- User session data
- Shopping cart
πΉ 5. Application Scope (Web)¶
π One bean per ServletContext
π§ Behavior¶
- Shared across entire web app
πΉ 6. WebSocket Scope¶
π One bean per WebSocket session
π Summary Table¶
| Scope | Instances | Lifecycle | Use Case |
|---|---|---|---|
| Singleton | 1 | App-wide | Services |
| Prototype | Many | Partial | Stateful objects |
| Request | Per request | Request | API data |
| Session | Per session | Session | User data |
| Application | 1 per app | App | Global config |
β οΈ Important Interview Trap¶
β Singleton + Prototype together¶
π Problem:
- Prototype injected only once into singleton π¬
β Solution:¶
Use:
ObjectProviderApplicationContext.getBean()
π― Interview Answer¶
βSpring supports multiple bean scopes like singleton, prototype, request, session, and application. Singleton is the default and creates a single shared instance, while prototype creates a new instance on each request. Web scopes like request and session are used in web applications for managing request-specific and user-specific data.β
π§ Mental Model¶
Think of scopes like hotel rooms π¨:
- Singleton β one VIP suite (shared)
- Prototype β new room every booking
- Request β room for one visit
- Session β room for entire stay