Bean Scopes and Lifecycle: How Objects Live and Die
Explore singleton vs prototype scopes, thread safety traps, and lifecycle hooks with @PostConstruct and @PreDestroy.
01The two main bean scopes
When you ask Spring for a bean, how many instances exist?
By default, Spring does not create a new object every time. It uses the Singleton scope.
Think of the office coffee machine:
- Singleton scope (Default): There is one shared coffee machine on the floor. Every employee uses the exact same machine.
- Prototype scope: Every time you press the button, you get a brand-new disposable paper cup just for you.
| Scope | Instances Created | Use Case |
|---|---|---|
singleton (Default) | Exactly one instance per Spring IoC container | Stateless services, controllers, repositories, configuration classes. |
prototype | A new instance every time the bean is requested | Stateful objects that carry per-operation mutable data. |
request (Web only) | One instance per HTTP request | Per-request context, audit metadata, security tokens. |
session (Web only) | One instance per HTTP user session | E-commerce shopping cart, user session profile. |
application (Web only) | One instance per ServletContext | Web application-wide state. |
To change a bean's scope from the default singleton, annotate it with @Scope:
@Component
@Scope("prototype")
public class ReportGenerator {
// A fresh object is created each time
}02The deadly Singleton thread safety trap ⚠️
Because Spring singleton beans are shared across all concurrent HTTP requests, they must always be stateless.
Look at this disastrous bug:
@Service
public class UserService {
// DANGER! Shared mutable field on a singleton bean!
private User currentUser;
public void process(User user) {
this.currentUser = user; // Thread A sets Alice
// Context switch! Thread B sets Bob!
chargeMoney(this.currentUser); // Thread A now charges Bob instead of Alice!
}
}Because Tomcat handles requests using a thread pool, multiple threads execute the methods of UserService simultaneously. Storing user-specific data in an instance variable creates severe race conditions and data leaks.
03The Bean Lifecycle Journey
Every Spring Bean travels along a strictly orchestrated path from birth to death:
1. Instantiation
Spring calls the bean's constructor (new UserService(...)) using reflection.
2. Populate Properties (Dependency Injection)
Spring injects all required dependencies into constructor or fields.
3. Aware Interfaces
If your bean implements special interfaces like BeanNameAware or ApplicationContextAware, Spring hands the bean its own name and container reference.
4. Initialization Hook (@PostConstruct)
Spring executes methods marked with @PostConstruct. At this stage, all dependencies are fully wired and safe to use.
5. In Service (Active)
The bean is ready and serves incoming application requests.
6. Destruction Hook (@PreDestroy)
When the application shuts down gracefully, Spring calls methods annotated with @PreDestroy to release system resources.
04Clean initialization and teardown code
package com.veltoryx.demo.cache;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class CurrencyCache {
private final Map<String, Double> rates = new ConcurrentHashMap<>();
public CurrencyCache() {
// Step 1: Constructor. Keep it lightweight!
// Never call external APIs or databases here.
}
@PostConstruct
public void init() {
// Step 4: Runs once all dependencies are injected.
// Perfect place to warm up caches or verify network connections!
rates.put("USD", 1.0);
rates.put("EUR", 0.92);
rates.put("INR", 83.5);
System.out.println("CurrencyCache initialized with " + rates.size() + " rates.");
}
public double getRate(String currency) {
return rates.getOrDefault(currency, 1.0);
}
@PreDestroy
public void cleanup() {
// Step 6: Graceful shutdown
rates.clear();
System.out.println("CurrencyCache flushed. Sockets closed.");
}
}05Prototype bean destruction caveat
There is one major gotcha with @Scope("prototype") beans:
- Spring creates the prototype bean, runs
@PostConstruct, and hands it to you. - But Spring does not manage the destruction of prototype beans.
- The
@PreDestroymethod will never be invoked automatically on prototype beans. The client code is responsible for cleaning up resources.
06In the interview
Common follow-up questions:
- Are Spring beans thread-safe? Not inherently. Singleton beans are shared across all threads; they are only thread-safe if you make them stateless. If a singleton bean holds mutable state in an instance variable, it is not thread-safe.
- What is the difference between
@PostConstructandInitializingBean? Both run at the exact same point in the lifecycle.@PostConstructis a standard Jakarta annotation (jakarta.annotation.PostConstruct) and decouples your code from Spring interfaces.InitializingBeanis a Spring-specific interface withafterPropertiesSet(), which tightly couples your code to the framework. Modern code always prefers@PostConstruct.
07Check your understanding
Quiz · 4 questions
0 of 4 answered
1. What is the default scope of a Spring Bean if no @Scope annotation is provided?
2. Why is it dangerous to store a user ID in an instance variable of a @Service bean?
3. At what point in the bean lifecycle does a method annotated with @PostConstruct execute?
4. Does Spring automatically invoke @PreDestroy on a bean with prototype scope?