22

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.

Stephen Kennedy
  • 18,869
  • 22
  • 90
  • 106
Learner
  • 223
  • 1
  • 2
  • 6

1 Answers1

43

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.

rohanagarwal
  • 711
  • 8
  • 30
dknight
  • 549
  • 5
  • 7
  • Thanks a lot for the confirmation – Learner Feb 02 '18 at 03:44
  • 12
    Can you please update your answer with reference to documentation that supportings your `thread-safe` explanation? – Raf Dec 09 '18 at 20:31
  • @Raf, this can be confirmed too by looking at the source code beginning from `org.springframework.web.context.support.WebApplicationContextUtils.RequestObjectFactory`. – Jaime Hablutzel Jan 31 '20 at 01:14
  • 1
    Now I wonder how it could work at other Spring beans than Controller. Especially when it comes to asynch invocations as well as circuit-breaker (semaphore) kinds, that's not ThreadLocal involved. After I check the hierarchy, I've learned StandardServletAsyncWebRequest exists, but still not sure of the best practices/examples. Any references or docs, please share with us? Thanks. – Brendan Kim Jan 26 '21 at 14:02