Spring Bean Lifecycle and Scopes

Interview Preparation Hub for Backend and Cloud-Native Engineering Roles

1. Introduction

In Spring, beans are the core objects managed by the IoC container. Understanding the bean lifecycle (creation β†’ initialization β†’ usage β†’ destruction) and bean scopes (singleton, prototype, request, session, etc.) is essential for designing scalable and maintainable applications.

2. Bean Lifecycle Phases

  • Instantiation: Container creates the bean instance.
  • Populate Properties: Dependencies injected.
  • Bean Awareness: Interfaces like BeanNameAware, BeanFactoryAware.
  • Pre-Initialization: BeanPostProcessor logic before init.
  • Initialization: Custom init methods or @PostConstruct.
  • Post-Initialization: BeanPostProcessor logic after init.
  • Usage: Bean ready for application logic.
  • Destruction: Cleanup via @PreDestroy or DisposableBean.
Diagram: Spring Bean Lifecycle

[Container Starts] β†’ Instantiation β†’ Populate Properties β†’ Awareness Interfaces β†’ Pre-Init β†’ Init β†’ Post-Init β†’ Bean Ready β†’ Destruction β†’ [Container Ends]

3. Realistic Example: Payment Processing System

Imagine a payment system where PaymentService bean requires initialization (connecting to gateway) and destruction (closing connections).

@Component
public class PaymentService implements InitializingBean, DisposableBean {
  @Override
  public void afterPropertiesSet() {
    System.out.println("Connecting to Payment Gateway...");
  }

  @Override
  public void destroy() {
    System.out.println("Closing Payment Gateway connection...");
  }
}
    

This ensures resources are properly managed during the bean’s lifecycle.

4. Bean Scopes

Scope Description Realistic Example
Singleton One instance per container. Shared TransactionService across app.
Prototype New instance every request. Each LoanApplication form.
Request One instance per HTTP request. RequestLogger for each API call.
Session One instance per HTTP session. UserProfile per logged-in user.
Application One instance per ServletContext. AuditService shared globally.
WebSocket One instance per WebSocket session. ChatSession for real-time messaging.

5. Diagram: Bean Scopes in Web Application

Diagram: Bean Scopes

Singleton β†’ Shared across all requests
Prototype β†’ New object each time
Request β†’ New bean per HTTP request
Session β†’ Bean tied to user session
Application β†’ Bean tied to app context
WebSocket β†’ Bean tied to WebSocket connection

6. Best Practices

  • Use singleton for stateless services.
  • Use prototype for stateful, short-lived objects.
  • Release resources in destroy methods.
  • Leverage @PostConstruct and @PreDestroy for clarity.
  • For web apps, use request/session scopes carefully to avoid memory leaks.

7. Common Mistakes

  • Storing state in singleton beans β†’ concurrency issues.
  • Using prototype beans without cleanup β†’ memory leaks.
  • Misusing session scope β†’ excessive memory usage.
  • Ignoring lifecycle callbacks β†’ uninitialized resources.

8. Interview Notes

  • Be ready to explain lifecycle phases with examples.
  • Discuss singleton vs prototype scope differences.
  • Explain request/session scope in web apps.
  • Know how to implement custom init/destroy methods.
  • Understand BeanPostProcessor role in lifecycle customization.

9. Summary

The Spring Bean Lifecycle defines how beans are created, initialized, used, and destroyed, while bean scopes determine their lifespan and visibility. Together, they ensure efficient resource management and flexible application design. For interviews, focus on lifecycle phases, scope differences, realistic examples, and best practices. Mastery of these concepts demonstrates readiness for backend engineering and cloud-native development roles.