Sub topic 14
Injecting shorter-lived beans into singletons
This chapter assumes you know basic Spring dependency injection (@Component, @Autowired, constructor injection), the difference between singleton and prototype scope, and what the request and session scopes are. It covers why a singleton that depends on a shorter-lived bean breaks, and the three standard ways to fix it.
The scope mismatch problem
A singleton bean is created once, and its dependencies are injected once, while the container builds it. If one of those dependencies is a prototype bean, the singleton receives a single instance at that moment and keeps it for the life of the application. The prototype scope says "a new instance on every request to the container", but the container is only asked once.
The same happens with web scopes. A request-scoped bean needs an active HTTP request. When the singleton is built at startup, there is no request. Spring then fails with an error such as Scope 'request' is not active for the current thread.
The rule is simple: a bean can only hold a direct reference to a bean that lives at least as long as itself. A shorter-lived dependency must be looked up each time you need it.
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 BrokenRunner {
private final Job job;
BrokenRunner(Job job) {
this.job = job;
}
Job currentJob() {
return job; // always the same instance
}
}Every call to currentJob() returns the same Job. Nothing in the code looks wrong, which is why this is a common bug.
Fix 1: ObjectProvider
ObjectProvider<T> is a Spring type that defers the lookup. You inject the provider, not the bean, and ask it for an instance when you need one. 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();
}
}ObjectProvider also works for request and session beans, as long as you call getObject() while the scope is active, for example inside a controller method. It has useful extras:
getIfAvailable()returnsnullinstead of throwing when no bean exists.getIfUnique()returnsnullwhen there are zero or several candidates.stream()returns all matching beans.
The standard jakarta.inject.Provider<T> behaves similarly if you want to avoid a Spring type in your signatures.
The cost is that your code now depends on the lookup mechanism. That is acceptable, and it is explicit: a reader sees that a fresh instance is requested each time.
Fix 2: scoped proxies
A scoped proxy keeps the code looking like ordinary injection. Spring injects a proxy object that implements the same type as the target bean. The proxy lives as long as the singleton. On each method call, the proxy asks the container for the real bean in the current scope (for example, the current request) and forwards the call to it.
For web scopes, the composed annotations @RequestScope, @SessionScope and @ApplicationScope create a scoped proxy by default.
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();
}
}AuditService is a singleton, yet currentRequestId() returns a different value for each HTTP request. The requestInfo field holds a proxy, and each call to id() is routed to the instance bound to the current request.
Declaring a proxy yourself
For a prototype or a custom scope, you must ask for the proxy with proxyMode:
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
class Ticket {
private static int counter = 0;
private final int number = ++counter;
int number() {
return number;
}
}TARGET_CLASS uses a class-based (CGLIB) proxy. INTERFACES uses a JDK dynamic proxy and requires the bean to implement an interface that the injection point uses. NO means no proxy, which is the default for @Scope.
Proxy gotchas
A proxy for a prototype bean creates a new target on every method call, not on every injection. Two calls in a row, ticket.number() and ticket.number(), return different numbers. Use this only when the bean is stateless between calls, or when a fresh object per call is what you want. If you need to call several methods on the same instance, use ObjectProvider and keep the result in a local variable.
Other limits of class-based proxies:
- The class cannot be
final, and proxied methods cannot befinalorprivate. - Calls made directly on
thisinside the target bypass the proxy. - Accessing a public field through the proxy reads the proxy's field, not the target's. Use methods.
toString()andequals()go through the proxy, so do not compare a proxy to a raw instance.
Fix 3: lookup method injection
You can also let Spring override a method so that it returns a fresh bean each time. Annotate an abstract or overridable method with @Lookup:
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component
abstract class LookupRunner {
@Lookup
protected abstract Job createJob();
void run() {
Job job = createJob(); // new Job each call
System.out.println(job);
}
}Spring generates a subclass with CGLIB and implements createJob() as a container lookup. It works well and keeps the class free of container types, but it needs a non-final class and a component-scanned or @Bean-registered declaration. Most teams prefer ObjectProvider because it is easier to test and easier to read.
Choosing an approach
| Situation | Best choice |
|---|---|
| Need a new prototype instance, and want to hold it across several calls | `ObjectProvider` |
| Need the current request or session bean, with natural-looking injection | Scoped proxy (the default for web scope annotations) |
| Dependency is optional | `ObjectProvider.getIfAvailable()` |
| You want no container types in the class | Scoped proxy or `@Lookup` |
| Bean is a final class or has final methods | `ObjectProvider` |
Lifecycle effects to remember
Destruction callbacks still do not run for prototype beans, even when you obtain them through ObjectProvider or a proxy. The container creates them and hands them over, then forgets them. If a prototype holds a resource, the code that asks for it must release it.
A scoped proxy bean is itself a singleton. The container registers the proxy under the original bean name and moves the real bean definition to a name prefixed with scopedTarget.. If you look up beans by name or type in tests, you may see both.
A request-scoped target is destroyed when the request ends, so @PreDestroy on a request-scoped bean does run. Calling the proxy after the request has finished, for example from a background thread you started, fails with the "scope is not active" error again. Pass the data you need to the other thread instead of the proxy.
Exercise
A singleton ReportService has a constructor parameter of type Report, which is annotated @Scope("prototype") with no proxy mode. The team expects each call to generate() to use a new Report, but all reports share state. Explain the cause and give two ways to fix it.
Show answer
The container injects Report once, when it builds the singleton, so every call to generate() uses that single instance. Fix 1: inject ObjectProvider<Report> and call getObject() inside generate(), which returns a new instance each time and lets you keep it in a local variable for the rest of the method. Fix 2: change the scope annotation to @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS), so the singleton holds a proxy. This creates a new target on each method call, so it only suits cases where each call is independent.
Exercise
A request-scoped bean is injected into a singleton using @RequestScope. A developer starts a new thread with CompletableFuture.runAsync inside a controller method, and the lambda calls a method on the singleton that uses the request-scoped bean. It throws "Scope 'request' is not active for the current thread". Why, and what is a safe fix?
Show answer
The request scope is bound to the thread that handles the HTTP request. The new thread has no request attributes, so the proxy cannot find a target bean. A safe fix is to read the needed values (for example the request ID) in the controller thread and pass them as plain method arguments to the asynchronous code.