springspring-mvc

@Autowired HttpServletRequest vs passing as parameter - best practice


Assume we have defined a controller class which has @Controller annotation only.

Inside the class, we have defined private @Autowired HttpServletRequest request; variable.

Spring Controllers are Singleton. When we defined HttpServletRequest as @Autowired in a web-application, will it be an issue?

I read from a web-site that even though it is @Autowired it just injects a proxy for the thread variable.

Is it true? In a multi-threaded environment can we use @Autowired or passing HttpServletRequest as a parameter to each method in the controller class would be the right approach?

Some websites says it is an issue and suggested to pass as a parameter whereas few say it will be an issue.

I don't understand which one is right.


Solution

  • Both are ok.
    @Autowired HttpServletRequest and passing as a parameter are the same things.

    Before passing HttpServletRequest to invocation method responding to @RequestMapping function, Spring stores the HttpServletRequest into a ThreadLocal type variable.

    That ThreadLocal variable is a thread-safe map that keeps HttpServletRequest in the current thread context. The @Autowired HttpServletRequest proxy bean gets the correct request from that ThreadLocal variable.