Reputation:
Let's say I have a Spring controller.
@RequestMappin("/path")
public MyController {
}
As stated, default scope of the controller is Singleton. I know that I can autowire request in REQUEST scope beans, however, if I try to autowire request, so that
@RequestMappin("/path")
public MyController {
@Autowired
private HttpServletRequest request;
}
It still works, and for each request I get appropriate request object. Does it mean that autowire works regardless the scope is request or not?
Upvotes: 9
Views: 12281
Reputation: 874
If you don't want to use @Autowired
you can get HttpServletRequest
in this way:
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Upvotes: 0
Reputation: 350
When a spring web based application bootstraps, it will register the bean of type ServletRequest
,ServletResponse
,HttpSession
,WebRequest
with the support of ThreadLocal variables. So whenever you request one kind of above four, the actual value will be the actual stored ThreadLocal variable that are bound to the current thread.
You can find the details implementation mechanisms of @Autowired HttpServletRequest at @Autowired HttpServletRequest
Upvotes: 10
Reputation: 14550
if it works that means spring doesn't inject exactly http request but a proxy. the proxy delegates calls to current http request
Upvotes: 10
Reputation: 1438
You can get HttpServletRequest
object in each webservice method. Such as:
@RequestMapping("/method")
public void method(HttpServletRequest req) {
// ...
}
Upvotes: 2