Thursday, May 10, 2012

Injecting in HttpServletRequest to a Spring Bean

This is a little counter intuitive, you can actually inject in HttpServletRequest into any Spring component!

For eg:

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

public class HttpRequestServiceImpl implements HttpRequestService{

 @Autowired private HttpServletRequest httpServletRequest;
 public String getAttribute(String name) {
  return (String)this.httpServletRequest.getAttribute(name);

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.

1 comment:

  1. This is the kind of clarification I was looking for: concise, clear and complete.
    Many thanks!