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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With