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.