Sub topic 14
Injecting shorter-lived beans into singletons
This chapter assumes you know basic Spring dependency injection (@Component, @Autowired, @Bean) and the difference between singleton, prototype and web scopes. It covers what goes wrong when a long-lived bean depends on a shorter-lived one, and two ways to fix it.
The scope mismatch
A singleton is created once, and its dependencies are injected once, while the singleton is being created. If one of those dependencies is a prototype or a request-scoped bean, the singleton receives one instance at that moment and keeps it for as long as it lives.
For a prototype, this means every use of the field sees the same object, even though the scope promises a new one per injection point lookup. For a request-scoped bean, the problem is worse. At startup there is no HTTP request, so Spring cannot create the bean and fails with a scope-not-active error.
Fix 1: ObjectProvider
ObjectProvider<T> is a handle to the container. The singleton injects the provider instead of the bean, then asks it for an instance whenever one is needed. For a prototype bean, each getObject() call returns a new instance.
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class Job {
}
@Service
class JobRunner {
private final ObjectProvider<Job> jobs;
JobRunner(ObjectProvider<Job> jobs) {
this.jobs = jobs;
}
Job newJob() {
return jobs.getObject();
}
}The lookup is explicit. Your code shows exactly when a new instance is requested, and the singleton depends on Spring's API.
Fix 2: a scoped proxy
A scoped proxy is a stand-in object that implements the same type as the real bean. The singleton receives the proxy once. On every method call, the proxy finds the real bean for the current scope (for example, the current request) and forwards the call to it.
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
class RequestInfo {
private final String id = UUID.randomUUID().toString();
String id() {
return id;
}
}
@Service
class AuditService {
private final RequestInfo requestInfo;
AuditService(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
String currentRequestId() {
return requestInfo.id();
}
}@RequestScope creates a scoped proxy by default, so AuditService can be a singleton and still see a different RequestInfo for each request. The same applies to @SessionScope. For other scopes, set proxyMode on @Scope, for example @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS).
Common errors
- Calling the proxy outside the scope. Using
requestInfo.id()on a background thread, or at startup, throws an exception because no request is active. - Expecting a new prototype per call through a proxy. A proxied prototype creates a new target on each method call, so state set in one call is not visible in the next. This is rarely what you want. Use
ObjectProviderfor prototypes. - Final classes and methods. With class-based proxies, the proxy subclasses your bean, so
finalclasses and methods cannot be proxied correctly. - Reading fields directly. Access state through methods. Fields on the proxy object are not the target's fields.
Choosing between them
| Situation | Use |
|---|---|
| Need a new prototype each time | `ObjectProvider` |
| Request or session data used by a singleton | Scoped proxy |
| Want the lookup to be visible in code | `ObjectProvider` |
| Want the singleton to stay unaware of scopes | Scoped proxy |
Exercise
A singleton service has a field of a request-scoped bean type, injected without a proxy. What happens when the application starts, and how do you fix it?
Show answer
Startup fails because no HTTP request is active, so Spring cannot create the request-scoped bean. Fix it by using @RequestScope, which adds a scoped proxy by default, or by setting proxyMode on @Scope, or by injecting an ObjectProvider of the bean and calling getObject() during a request.
Exercise
Why does a singleton that injects a prototype bean directly always see the same object?
Show answer
Injection happens once, when the singleton is created. The container hands over one prototype instance at that moment, and the singleton keeps that reference. Use ObjectProvider to request a new instance on each call.