Bean lifecycle and scopes
Mid-level Always asked 6 min
On this page
The question
What is the lifecycle of a Spring bean?
30-second answer
The container calls the constructor, then runs field and setter injection. Next come Aware callbacks and BeanPostProcessors, then @PostConstruct, afterPropertiesSet and any initMethod. Post-processors run again, and this is where a proxy may wrap the bean. It then serves calls until the context closes, when @PreDestroy, destroy and any destroyMethod run.
Understand it
A singleton bean from constructor to destroy
Step by stepThe container calls the constructor. Constructor arguments are ready, but a field marked @Autowired is still null, so do not use one here.
View as text
Ten rows in order, grouped as Create, Initialize, Use and Destroy, with the current row highlighted. A mark below says whether an @Autowired field is null or set.
The container calls the constructor. Constructor arguments are ready, but a field marked @Autowired is still null, so do not use one here.
Now field and setter injection run. Every dependency is in place, though the bean has not been told it is ready.
If the bean asked for them, the container passes its name and other details through interfaces such as BeanNameAware.
Every BeanPostProcessor sees the bean before initialization. This is the framework hook that makes @PostConstruct work.
@PostConstruct runs: the right place for setup that needs the injected dependencies, such as checking settings or loading a cache.
Then afterPropertiesSet from InitializingBean, then any initMethod declared on @Bean. These are older ways to do the same setup.
BeanPostProcessors run again. This is where a proxy can replace the bean, so @Transactional on a self-call during @PostConstruct does nothing.
The bean is ready. Other beans hold it, and it serves calls until the application context closes.
On shutdown, @PreDestroy runs first: close connections and flush buffers. A prototype bean never gets this callback.
Then destroy from DisposableBean, then any destroyMethod on @Bean. The bean is gone, along with the context.
Ten rows in order, grouped as Create, Initialize, Use and Destroy, with the current row highlighted. A mark below says whether an @Autowired field is null or set.
The container calls the constructor. Constructor arguments are ready, but a field marked @Autowired is still null, so do not use one here.
Now field and setter injection run. Every dependency is in place, though the bean has not been told it is ready.
If the bean asked for them, the container passes its name and other details through interfaces such as BeanNameAware.
Every BeanPostProcessor sees the bean before initialization. This is the framework hook that makes @PostConstruct work.
@PostConstruct runs: the right place for setup that needs the injected dependencies, such as checking settings or loading a cache.
Then afterPropertiesSet from InitializingBean, then any initMethod declared on @Bean. These are older ways to do the same setup.
BeanPostProcessors run again. This is where a proxy can replace the bean, so @Transactional on a self-call during @PostConstruct does nothing.
The bean is ready. Other beans hold it, and it serves calls until the application context closes.
On shutdown, @PreDestroy runs first: close connections and flush buffers. A prototype bean never gets this callback.
Then destroy from DisposableBean, then any destroyMethod on @Bean. The bean is gone, along with the context.
Takeaway: Constructor, injection, @PostConstruct, then a long life in use, then @PreDestroy. Use @PostConstruct for setup that needs dependencies, and remember a proxy only wraps the bean afterward.
Scopes: how many instances do four calls see?
ExploreThe trap: a prototype injected into a singleton is created once, when the singleton is built, so every call shares it. It behaves like a singleton.
View as text
A singleton holder box above two requests, each making two calls. Each call shows the number of the instance it received, and a mark counts the distinct instances.
Singleton, the default: one shared instance for the whole context, whatever the holder does. It must be safe to use from many threads. Four calls see instance 1.
The trap: a prototype injected into a singleton is created once, when the singleton is built, so every call shares it. It behaves like a singleton. Four calls see instance 1.
ObjectProvider asks the container on every call, so a prototype really is new each time. @Lookup does the same. Four calls see instances 1, 2, 3 and 4.
@RequestScope injects a proxy. The singleton keeps one proxy, and each call finds the instance of the current request: one per request. Request 1 sees instance 1 twice, and request 2 sees instance 2 twice.
No proxy: the singleton needs the bean at startup, when no request exists. The context fails with ScopeNotActiveException. A mark reads that the context fails.
A singleton holder box above two requests, each making two calls. Each call shows the number of the instance it received, and a mark counts the distinct instances.
Singleton, the default: one shared instance for the whole context, whatever the holder does. It must be safe to use from many threads. Four calls see instance 1.
The trap: a prototype injected into a singleton is created once, when the singleton is built, so every call shares it. It behaves like a singleton. Four calls see instance 1.
ObjectProvider asks the container on every call, so a prototype really is new each time. @Lookup does the same. Four calls see instances 1, 2, 3 and 4.
@RequestScope injects a proxy. The singleton keeps one proxy, and each call finds the instance of the current request: one per request. Request 1 sees instance 1 twice, and request 2 sees instance 2 twice.
No proxy: the singleton needs the bean at startup, when no request exists. The context fails with ScopeNotActiveException. A mark reads that the context fails.
Takeaway: A singleton holds what it was given at creation. To get a shorter-lived bean inside it, go through ObjectProvider, @Lookup or a scoped proxy.
In code
@Component
class PriceCache {
private final PriceClient client;
private Map<String, Integer> prices;
PriceCache(PriceClient client) {
this.client = client;
}
@PostConstruct // dependencies are ready here
void load() {
prices = client.fetchAll();
}
@PreDestroy // not called for prototype beans
void clear() {
prices = Map.of();
}
}@Component
class ReportJob {
private final ObjectProvider<ReportBuilder> builders;
ReportJob(ObjectProvider<ReportBuilder> builders) {
this.builders = builders;
}
String run() {
ReportBuilder builder = builders.getObject(); // new each call
return builder.build();
}
}@Service
class ReceiptService {
Wrong private final List<String> lines = new ArrayList<>(); // one list for all concurrent requests
String build(Order order) { lines.clear(); lines.add(order.id()); return String.join("\n", lines); }
String buildSafely(Order order) {
Right List<String> lines = new ArrayList<>(); // a local: one list per call
lines.add(order.id());
return String.join("\n", lines);
}
}Solve it
“Scope ‘request’ is not active for the current thread” at startup
TenantContext holds the tenant id read from a request header, declared with @Scope("request"). ReportService, a
singleton, takes it in its constructor, and the app fails to start with that message. Fix it.
- Compare the lifetimes. The singleton is built once at startup, when no HTTP request exists. A request-scoped bean exists only during a request.
- See the mismatch. Injecting a short-lived bean into a long-lived one at construction time cannot work: which request’s instance would it hold?
- Inject a scoped proxy.
@RequestScopeuses a proxy by default. The singleton holds the proxy, and each call reaches the current request’s instance. - Watch the edges. The proxy still fails outside a request, such as in
@Asyncor@Scheduledcode. Pass the tenant id as a parameter there. - Check. Two concurrent requests with different tenant headers each see their own tenant.
Wrong @Component @Scope("request") // no proxy: the singleton cannot be built at startup
class TenantContextBroken { String tenantId; }
Right @Component @RequestScope // proxyMode = TARGET_CLASS by default
class TenantContext {
private String tenantId;
void set(String tenantId) { this.tenantId = tenantId; }
String tenantId() { return tenantId; }
}
@Service
class ReportService {
private final TenantContext tenant; // the proxy, the same for every request
ReportService(TenantContext tenant) { this.tenant = tenant; }
Report build() { return Report.forTenant(tenant.tenantId()); } // resolves the current request's instance
}How to answer
- Injected fields are still null in the constructor;
@PostConstructis safe. - AOP (aspect-oriented programming) proxies are applied after initialization.
- The setup callbacks run as
@PostConstruct, thenafterPropertiesSet, theninitMethod. - Prefer
@PostConstructand@PreDestroy, which do not tie a class to Spring interfaces.
Common mistakes
- Doing setup with an
@Autowiredfield inside the constructor, where it is still null. - Expecting
@Transactionalto work on a self-call made during@PostConstruct.
Follow-up questions
What is the difference between singleton, prototype and request scope?
A singleton, the default, is one instance per application context, created at startup and shared. A prototype is a new instance each time the container is asked. A request-scoped bean is one instance per HTTP request, and needs a web context. Session and application scopes exist too. A Spring singleton is one per context, not one per JVM (Java Virtual Machine).
- Most beans are stateless singletons.
- A prototype is new per lookup or injection, not per method call.
@RequestScopeis@Scope("request")with a proxy already configured.
See it in the infographic: Scopes: how many instances do four calls see?
What happens when you inject a prototype bean into a singleton?
The prototype is created once, when the singleton is built, and that same instance is used forever, so it behaves like a singleton. To get a new one per use, inject ObjectProvider and call getObject(), use a @Lookup method, or configure a scoped proxy. Each of those gives a new instance every time.
- Scope is applied when the container hands out the bean, not on each method call.
ObjectProvideravoids a dependency onApplicationContext.- The container forgets a prototype after creating it, so it never calls
@PreDestroy.
class ReportJob {
private final ObjectProvider<ReportBuilder> builders;
ReportJob(ObjectProvider<ReportBuilder> builders) {
this.builders = builders;
}
String run() {
return builders.getObject().build(); // new each call
}
} See it in the infographic: Scopes: how many instances do four calls see?
How can a singleton controller use a request-scoped bean?
Through a proxy. @RequestScope makes Spring inject a proxy into the singleton, and each method call on it finds the instance for the current request. Without a proxy, as with plain @Scope("request"), the singleton needs the bean at startup, when no request exists, and the context fails with ScopeNotActiveException.
- Calling the proxy outside a request throws the same exception.
ObjectProvideralso works: the lookup happens inside the request.- Instances live in the request, so a new thread does not see them.
See it in the infographic: Scopes: how many instances do four calls see?
Are Spring singleton beans thread-safe?
Not by themselves. The container creates one instance, and every request thread calls it at once, with no locking from Spring. A stateless bean with only final dependencies is safe. A mutable field, such as a counter or a request's data, is a race condition. Move that state to local variables, a request scope, or a concurrent type.
- Local variables live on each thread's stack, so they are safe.
- Use
AtomicIntegerorConcurrentHashMapfor state that really is shared. - Never keep data for one request in a singleton's field.
@Service
class OrderService {
private Order current; // a race: all threads share this
void place(Order order) {
Order current = order; // safe: a local variable
}
} See it in the infographic: Scopes: how many instances do four calls see?
Why is @PreDestroy not called on prototype beans?
The container creates and initializes a prototype, hands it over, and keeps no reference, so it cannot know when the bean is finished, and has nothing to destroy at shutdown. So @PostConstruct runs and @PreDestroy does not. If a prototype holds a resource, whoever asked for it must close it.
- Keeping references would be a memory leak, which is why the container does not.
- Making the bean
AutoCloseablelets callers use try-with-resources. - Singletons are destroyed in the reverse order of their dependencies.
See it in the infographic: A singleton bean from constructor to destroy
Why does @Transactional not apply to a method called from @PostConstruct in the same class?
The call goes through this, not through a proxy, so a self-call during @PostConstruct has no active transaction, while a call to another bean's @Transactional method from the same place does. Move the work to another bean, or run it from an ApplicationReadyEvent listener.
What is a BeanPostProcessor for?
It is a hook that sees every bean before and after initialization, and may return a different object. Spring itself uses it: one post-processor runs @PostConstruct, and another wraps beans in AOP proxies. You rarely write one, but it explains how annotations gain behavior.
When would you use ApplicationReadyEvent instead of @PostConstruct?
When the work needs the whole application to be up: every bean created and the server accepting requests. A @PostConstruct method runs while the context is still being built. An @EventListener(ApplicationReadyEvent.class) method runs after startup, through the proxy, so @Transactional and @Async work.
Check yourself
Show answers
- NullPointerException: Correct. The constructor runs first, and field injection only happens afterward.
- It works, because Spring injects first.: Incorrect. An object must exist before Spring can set one of its fields.
- Spring delays the constructor until the field is ready.: Incorrect. A constructor cannot run later than the object's creation. Use @PostConstruct, or constructor injection.
Show answers
- One: Correct. Injection happens once, when the singleton is built, so every call uses that same instance.
- Three: Incorrect. That would need a lookup on each call, through ObjectProvider or @Lookup.
- None, because the injection fails.: Incorrect. The injection is legal, which is why the trap goes unnoticed.
Show answers
- @PreDestroy: Correct. The container keeps no reference to a prototype, so it has nothing to destroy at shutdown.
- @PostConstruct: Incorrect. Initialization still runs. The container only forgets the bean after handing it over.
- The constructor: Incorrect. Every instance needs its constructor. A prototype runs it once per instance.