Tech Interview RoomStudy guides

Spring

Explain Spring bean scopes. How do you inject a prototype bean into a singleton? Are singletons thread-safe?

Intermediate · 2 min read · Lesson 2 of 8 in Spring

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 step and job scopes, 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:

  1. ObjectProvider<T> (preferred): provider.getObject().
  2. A @Lookup method that Spring overrides with CGLIB.
  3. 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

java
@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.