I recently stumbled upon the fact that it's possible to autowire HttpServletRequest into singleton-scoped Spring beans, despite the object being specific to a particular web request, and not globally applicable. From what I've been able to determine, this is a proxy object registered by WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, servletContext). It is added by spring-web (and/or by spring-boot) to the bean factory by AbstractRefreshableWebApplicationContext (or its subclass overrides).

Looking at the source for WebApplicationContextUtils, it looks like the following objects are provided in this manner:

  • ServletRequest
  • ServletResponse
  • HttpSession
  • WebRequest
  • FacesContext (if JSF present)
  • ExternalContext (if JSF present)

While handy, this behavior was somewhat surprising, since I didn't expect to be able to autowire in something that was inherently tied to a specific web request to a singleton bean that is shared across requests.

From what I have been able to tell (as discussed in this Stack Overflow question), this feature is not documented anywhere obvious. The only documentation I've seen is the issue that added it (https://github.com/spring-projects/spring-framework/issues/9808#issuecomment-453333642) and the release notes when it was added:

As of Spring 3.0 RC1, we generally inject proxies for request and session objects now. This has the advantage of working in singleton beans and serializable beans as well, and to always obtain the current session handle - even in case of invalidation between requests or between multiple calls within the same request.

It would be helpful if this feature were documented. In particular, it would be nice to have documentation that these beans are available for autowiring and the situations when they are not available (e.g. when executing outside of the scope of a request).