Explain Spring bean scopes. How do you inject a prototype bean into a singleton? Are singletons thread-safe?
Scopes
- singleton (default): one instance per container.
- prototype: a new instance every time it is requested from the container.
- Web scopes: request, session, application, websocket.
- Custom scopes (for example Spring Batch's
stepandjobscopes, or refresh scope in Spring Cloud).
Prototype inside a singleton
Injection happens once, when the singleton is created, so a prototype injected directly behaves like a singleton. Ways to get a fresh instance each time:
ObjectProvider<T>(preferred):provider.getObject().- A
@Lookupmethod that Spring overrides with CGLIB. - A scoped proxy:
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS), which creates a new target on every method call (often surprising). Request- and session-scoped beans injected into singletons must be scoped proxies, so each call resolves the instance for the current request.
Thread safety
Spring does nothing to make singletons thread-safe. They are shared by all request threads, so they must be stateless (only final references to other stateless beans and configuration) or protect their mutable state (concurrent collections, atomics). A per-request value stored in a field of a singleton is a classic production bug: users see each other's data.
Example
@Service
class ReportService {
private final ObjectProvider<ReportBuilder> builders; // ReportBuilder is @Scope("prototype")
ReportService(ObjectProvider<ReportBuilder> builders) { this.builders = builders; }
Report build(Criteria c) {
ReportBuilder b = builders.getObject(); // fresh, stateful builder per call
return b.with(c).build();
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
Why do request-scoped beans fail inside @Async methods?
Request scope is bound to the current HTTP request through a ThreadLocal (RequestContextHolder). An @Async method runs on another thread, where no request is bound, so accessing the scoped proxy throws IllegalStateException: No thread-bound request found. Pass the needed values as method arguments, or use a TaskDecorator to copy context explicitly.