Explain Spring bean scopes and lifecycle, and the bugs they cause.
BackendMid-level
In shortBeans are singletons by default: one shared instance per context, created at startup and used concurrently, so they must be stateless or thread-safe. Prototype, request and session scopes exist for state with shorter lifetimes, and injecting a shorter-lived bean into a singleton needs a proxy or a provider.
Model answer
Singleton (default): one instance per application context, created at startup (unless lazy), shared by every request thread. Fields must be immutable dependencies; storing per-request state in a field (private User currentUser) is a data race and leaks data between users.
Other scopes:
- Prototype: a new instance per injection or
getBean. Spring doesn’t manage its destruction. - Request / session: one instance per HTTP request or session (web contexts).
The classic bug: injecting a prototype or request-scoped bean into a singleton injects one instance, once, at startup. To get a fresh or current one each time, inject ObjectProvider<T> and call getObject(), or declare the scoped bean with proxyMode = ScopedProxyMode.TARGET_CLASS so a proxy resolves the current instance on each call.
Lifecycle: constructor (dependencies via constructor injection, which makes them final and testable) → property injection → @PostConstruct (initialization that needs dependencies) → in use → @PreDestroy on shutdown (close resources). For things that should start after the context is ready (consumers, schedulers), use SmartLifecycle or ApplicationReadyEvent rather than doing work in constructors.
Keep beans stateless, use constructor injection, and put request data in method parameters or a request-scoped object accessed through a provider.
What they're looking for
Singleton default and its thread-safety implication, other scopes, the scoped-proxy problem, lifecycle callbacks (constructor, @PostConstruct, @PreDestroy), and constructor injection.
Common mistakes
- Storing per-request data in a field of a singleton service.
- Injecting a prototype into a singleton and expecting a new instance per use.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior