Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is autowiring of HttpServletRequest into arbitrary Spring components documented?

Today, I discovered that it is possible to autowire HttpServletRequest into arbitrary singleton Spring beans.

@Component
public class MyComponent {
    private final HttpServletRequest servletRequest;

    public MyComponent(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
    }
}

I haven't found an authoritative source, but from what I can tell from searching online, this is actually a wrapper that delegates to the actual HttpServletRequest of the running thread.

For instance, this blog post from 2012 states:

So when multiple requests come to this service, how is the correct httpServletRequest corresponding to the user request injected into this service object. The answer is that a real HttpServletRequest is not really injected, only a proxy is injected in. The proxy is internally a reference to RequestContextHolder which at some point binds the HttpServletRequest to a threadlocal variable.

It's unclear to me whether this is a core Spring feature, a feature of Spring MVC, or something provided by Spring Boot.

I have not had any luck finding an authoritative source (e.g. in the Spring documentation, the internals of Spring, or the Spring release notes) explaining that this works, is a supported feature, and explaining how it works. I'm guessing it's there, but I'm not having luck finding it. If I'm going to be using a feature such as this, I would much prefer to have this context so that I can reason about when and how best to use it, and when to avoid it.

Where is this feature documented?

Note: This is a similar question to Inject HttpServletRequest into Controller. However, that is asking about the pitfalls of this approach and how it works, and does not address where or how it's documented or otherwise specified.

like image 356
M. Justin Avatar asked Jan 31 '26 20:01

M. Justin


1 Answers

That possibility of autowiring the proxy for HttpServletRequest's is a part of Spring MVC, and sadly it's not documented properly.

The best you can find about it is in some release notes of spring-web:3.0.0. For example, take a look at the release notes of 3.0.0.M4 and especially at this issue where Juergen Hoeller (one of the main developers of String) talks about how it works since this version.

Also, feel free to check the sources (WebApplicationContextUtils, RequestContextHolder), they're well documented.

like image 102
amseager Avatar answered Feb 03 '26 08:02

amseager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!