Video in progress

Strong Middle 🌱 Spring

How can you inject a request-scoped bean into a singleton service, when the singleton is created at application startup?

With a scoped proxy. The singleton gets a proxy instead of the real bean; on every call the proxy finds the instance for the current HTTP request and forwards the call to it.

📖 Answer

@Component
@RequestScope // = @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
    private String tenantId;
    private String requestId;
    // getters/setters
}

@Component
class TenantFilter extends OncePerRequestFilter {
    private final RequestContext ctx;
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        ctx.setTenantId(req.getHeader("X-Tenant"));
        chain.doFilter(req, res);
    }
}

@Service
class InvoiceService {
    private final RequestContext ctx; // actually a proxy
    void create() { String tenant = ctx.getTenantId(); } // the value for this request
}

Internally, the proxy gets the real object from the current request attributes through RequestContextHolder (a ThreadLocal).

Outside an HTTP request (@Scheduled, an @Async thread, a Kafka listener) you get No thread-bound request found as soon as you touch it. Pass the values an @Async method needs as parameters.

In practice many teams prefer to pass the value as an explicit parameter instead of using request scope: it's visible, and easy to test.