🌱 Spring Boot – Bean Scopes

 


🌱 Spring Boot – Bean Scopes


1️⃣ What is a Bean Scope?

A Bean Scope defines the lifecycle and visibility of a Spring Beanβ€”
that is, how many instances of a bean are created and how long they live.

πŸ”Ή Why Bean Scopes Matter

  • Memory management
  • Performance
  • Thread safety
  • Correct behavior in web applications

πŸ”Ή Common Bean Scopes in Spring Boot

Scope Description
Singleton One instance per Spring container
Prototype New instance every time requested
Request One instance per HTTP request
Session One instance per HTTP session

βœ… Quick Summary

  • Bean scope controls bean creation & lifecycle
  • Choosing the wrong scope can cause bugs or memory leaks

❓ Interview / Exam Questions

Q1. What is a bean scope in Spring?
➑ It defines how long a bean lives and how many instances are created.


2️⃣ Singleton Scope (Default)

πŸ”Ή Definition

  • Default scope in Spring
  • Only ONE object is created per IoC container
  • Same instance is shared across the entire application
@Component
@Scope("singleton") // optional (default)
public class UserService { }

πŸ”Ή Internal Behavior (From PDF)

  • Bean is created at application startup
  • Eagerly initialized
  • Same hashCode appears for every request

πŸ“Œ Important:
Singleton β‰  Thread-safe
Thread safety depends on implementation, not scope.


βš™οΈ Advantages

  • Low memory usage
  • Faster access
  • Ideal for stateless services

❌ Disadvantages

  • Not suitable for request-specific or user-specific data

βœ… Quick Summary

  • Default scope
  • One object for whole application
  • Created at startup

❓ Interview / Exam Questions

  1. Is Singleton scope thread-safe?
    ❌ No, thread safety must be handled explicitly.
  2. When is a singleton bean created?
    ➑ At application startup (eager).

3️⃣ Prototype Scope

πŸ”Ή Definition

  • A new object is created every time the bean is requested
  • Bean is lazily initialized
@Component
@Scope("prototype")
public class User { }

πŸ”Ή Internal Behavior (From PDF)

  • Each API call produces a new instance
  • Different hashCodes appear
  • Spring manages creation only, not destruction

⚠️ Important:
@PreDestroy is NOT called for prototype beans.


βš™οΈ Advantages

  • Suitable for stateful beans
  • No shared state

❌ Disadvantages

  • Higher memory usage
  • Developer must manage cleanup

βœ… Quick Summary

  • New object every request
  • Lazy initialization
  • Spring does not manage full lifecycle

❓ Interview / Exam Questions

  1. Does Spring destroy prototype beans?
    ❌ No.
  2. When should prototype scope be used?
    ➑ For stateful or temporary objects.

4️⃣ Request Scope

πŸ”Ή Definition

  • One bean instance per HTTP request
  • Only applicable in web applications
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean { }

πŸ”Ή Internal Behavior (From PDF)

  • Bean created when HTTP request arrives
  • Destroyed after request completion
  • Lazy by nature

πŸ“Œ Why Proxy Needed?
Because singleton beans may depend on request-scoped beans.


βš™οΈ Use Cases

  • Request-specific data
  • Logging request metadata
  • Authentication context

βœ… Quick Summary

  • One object per HTTP request
  • Automatically destroyed
  • Requires proxy when injected into singleton

❓ Interview / Exam Questions

  1. Can request scope be used in non-web apps?
    ❌ No.
  2. Why is proxyMode required?
    ➑ To inject request-scoped bean into singleton.

5️⃣ Session Scope

πŸ”Ή Definition

  • One bean per HTTP session
  • Lives as long as the session is active
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean { }

πŸ”Ή Internal Behavior (From PDF)

  • Bean created when session starts
  • Same instance used across multiple requests
  • Destroyed when session expires

βš™οΈ Use Cases

  • User preferences
  • Shopping cart
  • Login state

❌ Disadvantages

  • High memory usage
  • Not suitable for large-scale systems

βœ… Quick Summary

  • One bean per session
  • User-specific data
  • Proxy required

❓ Interview / Exam Questions

  1. Difference between request and session scope?
    ➑ Request: per request, Session: per user session.
  2. When is session bean destroyed?
    ➑ On session timeout or invalidation.

6️⃣ Scope Interaction & Important Observations (From PDF)

πŸ”Ή Singleton + Request Scope

  • Singleton bean is created at startup
  • Request bean is created only when request arrives
  • Singleton does not get recreated

πŸ”Ή Scope Resolution Rule

A bean with shorter lifecycle
cannot be directly injected into a bean with longer lifecycle
without proxy


βœ… Quick Summary

  • Scope mismatch causes runtime issues
  • Proxy resolves lifecycle mismatch

❓ Interview / Exam Questions

  1. Can singleton depend on request bean?
    ➑ Yes, using proxy.
  2. Which scope is longest living?
    ➑ Singleton.

7️⃣ Best Practices (Added)

βœ” Use Singleton for:

  • Services
  • Repositories
  • Stateless logic

βœ” Use Prototype:

  • When object state must not be shared

βœ” Use Request / Session:

  • Only in web apps
  • With proxyMode

❌ Avoid session scope in microservices


🎯 FINAL INTERVIEW TAKEAWAYS

  • Singleton is default
  • Prototype is not fully managed
  • Request & Session need proxy
  • Scope questions are very common in interviews

 

Leave a Reply