Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Show how to inject a request-scoped bean into a singleton controller, and explain why the proxy is needed.

We annotate the bean with @RequestScope, which creates a scoped proxy with proxyMode TARGET_CLASS by default, or with @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS), and then inject it into the singleton controller as usual. The controller receives the proxy at startup, when no request exists, and every method call on the proxy looks up the instance belonging to the current request. Without the proxy, startup fails, because creating the singleton would need a request-scoped instance while no request scope is active.

Why this question is asked

Controllers are singletons: Spring creates one instance at startup and every request thread shares it. Yet we often want per-request data, such as a correlation id or the result of parsing a header, available in the controller and the services it calls. Injecting a request-scoped bean is the Spring way to do it, and it only works because of a proxy. Interviewers ask for the code and the explanation to see whether we understand that proxy, since the same mechanism explains many other Spring behaviours. In this answer, we will write the code, see the failure without a proxy, understand what the proxy does on each call, and check that it really keeps requests apart.

1A Quick Recap of the Problem

A singleton is created once, when the context starts. Its dependencies are injected at that moment and never change. A request-scoped bean, by contrast, must be a different instance for each HTTP request, and it can only exist while a request is active, because Spring stores it as an attribute of that request.

So there is a mismatch: the singleton needs something to hold in its field at startup, but the real request-scoped instance does not exist until a request arrives, and there will be many of them over time. The answer is to inject a stand-in object that always forwards to the right instance.

2Writing the Code

Here is a request-scoped bean that holds a correlation id, a filter that fills it, and a singleton controller that uses it.

Java
@Component
@RequestScope // proxyMode = TARGET_CLASS by default
public class RequestInfo {
private String correlationId;
public void setCorrelationId(String id) { this.correlationId = id; }
public String getCorrelationId() { return correlationId; }
}
@Component
class CorrelationFilter extends OncePerRequestFilter {
private final RequestInfo info;
CorrelationFilter(RequestInfo info) { this.info = info; }
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Correlation-Id")).orElse(UUID.randomUUID().toString());
info.setCorrelationId(id);
chain.doFilter(req, res);
}
}
@RestController
class OrderController { // singleton
private final RequestInfo info; // a proxy, injected once at startup
OrderController(RequestInfo info) { this.info = info; }
@GetMapping("/orders/{id}")
String get(@PathVariable long id) {
return "order " + id + " cid=" + info.getCorrelationId();
}
}
// GET /orders/7 with X-Correlation-Id: abc -> order 7 cid=abc
// GET /orders/8 with X-Correlation-Id: xyz -> order 8 cid=xyz

The explicit equivalent of @RequestScope is @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS). Notice also that the filter is a singleton bean too, so it receives the same kind of proxy. Spring Boot's RequestContextFilter binds the request to the thread before our filter runs, so the proxy can find the request there; if a filter needs the request scope, check that it is ordered after RequestContextFilter.

3What Fails Without the Proxy

If we use @Scope("request") with no proxy mode, the default is ScopedProxyMode.NO. Now, when Spring creates OrderController at startup, it must inject a real RequestInfo, so it asks the request scope for one. The request scope looks for the current request, finds none, because the application is still starting, and the context fails to start.

Java
@Component
@Scope("request") // no proxy
public class RequestInfo { /* ... */ }
// Application startup:
// UnsatisfiedDependencyException: Error creating bean with name 'orderController' ...
// ScopeNotActiveException: Error creating bean with name 'requestInfo':
// Scope 'request' is not active for the current thread; consider defining a scoped proxy
// for this bean if you intend to refer to it from a singleton
// Caused by: IllegalStateException: No thread-bound request found ...

The error message itself suggests the fix. Other workarounds, such as injecting ObjectProvider<RequestInfo> and calling getObject() inside each handler method, also work, because the lookup then happens during the request. The proxy simply does that lookup for us on every call.

4What the Proxy Does on Each Call

With TARGET_CLASS, Spring generates a CGLIB subclass of RequestInfo at startup, registers it under the name requestInfo, and registers the real bean definition under a hidden name, scopedTarget.requestInfo. The proxy holds no data. When the controller calls info.getCorrelationId(), the proxy asks the container for scopedTarget.requestInfo, the request scope looks in the current request's attributes, creates the instance if it is missing, and the proxy forwards the call to it.

Step throughOne call through the request-scoped proxy
OrderControllerRequestInfo proxyRequest scopeRequestInfo for this request
getCorrelationId()
get scopedTarget.requestInfo
look in current request attributes
create if missing (first use in request)
instance for this request
getCorrelationId()
"abc"

7 messages in order. Play them, or step through them one at a time.

The proxy is shared; the instance behind it changes per request.

5Checking That Requests Stay Apart

Because the lookup uses the request bound to the current thread, two concurrent requests on two threads each get their own instance, even though they call the same proxy in the same singleton. A quick MockMvc test confirms it.

Java
@WebMvcTest(OrderController.class)
@Import({RequestInfo.class, CorrelationFilter.class})
class OrderControllerTest {
@Autowired MockMvc mvc;
@Test
void eachRequestHasItsOwnInfo() throws Exception {
mvc.perform(get("/orders/7").header("X-Correlation-Id", "abc"))
.andExpect(content().string("order 7 cid=abc"));
mvc.perform(get("/orders/8"))
.andExpect(content().string(startsWith("order 8 cid=")))
.andExpect(content().string(not(containsString("abc")))); // no leftover from request 1
}
}

6Follow-up questions

Should we use INTERFACES or TARGET_CLASS proxy mode?

TARGET_CLASS creates a CGLIB subclass, so we can inject the concrete class, and it is the default for @RequestScope. INTERFACES creates a JDK dynamic proxy that implements the bean's interfaces, so injection points must use the interface type. INTERFACES avoids CGLIB limits such as final methods, but requires an interface. For simple holders, TARGET_CLASS is the usual choice.

What happens if we call the proxy from an @Async method or a scheduled job?

The proxy finds no request bound to that thread and throws the same ScopeNotActiveException with the no thread-bound request cause. The proxy only solves the startup timing problem; it does not make request data available on other threads. For that, the values must be passed explicitly or propagated.

Is there a cost to calling the proxy?

Each call does a bean lookup and a request attribute lookup before forwarding, which is small but not free. In a tight loop it is better to read the value once into a local variable. For typical use, a few calls per request, the cost is negligible.

7Conclusion

In this answer, we injected a request-scoped RequestInfo into a singleton controller with @RequestScope, which creates a CGLIB scoped proxy by default. The controller gets the proxy at startup, and each call on it looks up the instance for the current request, creating it on first use. Without the proxy, the context fails to start because the request scope is not active while singletons are created, and the error message itself suggests defining a scoped proxy.

What to say in the interviewAbout 80 seconds aloud

Open with

I would annotate the bean with @RequestScope, which is a shortcut for @Scope with value request and proxyMode TARGET_CLASS, and then inject it into the controller's constructor like any other bean.

Then, if they want more

For example a RequestInfo holder for a correlation id, filled by a filter and read in the controller. The reason the proxy is needed is timing: the controller is a singleton created once at startup, and at that moment there is no HTTP request, so a real request-scoped instance cannot exist.

With TARGET_CLASS, Spring creates a CGLIB subclass registered under the original bean name, and registers the real definition under scopedTarget.requestInfo. The controller holds the proxy.

On every method call, the proxy asks the container for the target, the request scope looks in the current request's attributes, which it finds through the thread-bound request, creates the instance on first use, and the proxy forwards the call. So concurrent requests each see their own instance through the same proxy.

Without a proxy, with plain @Scope request, the context fails at startup with a ScopeNotActiveException saying the request scope is not active and suggesting a scoped proxy. An alternative is ObjectProvider and getObject inside the handler method.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to inject a request-scoped bean into a singleton controller, and explain why...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/b30319ffac/