Skip to content

🌱 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

@Component
@Scope("singleton") // optional (default)
class MyService {}

🧠 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

@Component
@Scope("prototype")
class MyService {}

🧠 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

@Component
@Scope("request")
class RequestBean {}

🧠 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

@Component
@Scope("session")
class SessionBean {}

🧠 Behavior

  • Shared across requests in same session

βœ… Use When

  • User session data
  • Shopping cart

πŸ”Ή 5. Application Scope (Web)

πŸ‘‰ One bean per ServletContext

@Component
@Scope("application")
class AppBean {}

🧠 Behavior

  • Shared across entire web app

πŸ”Ή 6. WebSocket Scope

πŸ‘‰ One bean per WebSocket session

@Scope("websocket")

πŸ”„ 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

@Autowired
private PrototypeBean prototypeBean;

πŸ‘‰ Problem:

  • Prototype injected only once into singleton 😬

βœ… Solution:

Use:

  • ObjectProvider
  • ApplicationContext.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