@Autowired HttpServletResponse

By | December 14, 2017
Questions:

I’m looking for a way to autowire HttpServletResponse. It doesn’t work with spring out of the box, but I’ve found this description. This works but is sort of annoying, in that spring obviously has a mechanism to make objects request scoped (i.e. HttpServletRequest) and this seems to be a hack bolted on top.

Is there a way to hook into the same mechanism that spring uses for HttpServletRequest? And, any idea why spring team decided to only make HttpServletRequest autowire capable (and excluded HttpServletResponse)?

Answers:

Perhaps there is some workaround, but it’s not that obvious, because it’s not the way it’s meant to be. Spring MVC is meant to have singleton @Controller beans that provide @RequestMapping methods which take the request and response as arguments.

If you need the response in another place (the service layer) – don’t do it. The response should not go beyond the web (controller) layer.

To inject the response, you need:
– to store the response in a ThreadLocal
– to make a factory bean that returns the current response

About the example code you showed – I’m not sure if you are not going to need the factory bean to return a proxy (implementing HttpServletResponse), which in turn to return the current response. And it gets rather complicated.

But ultimately – you should not do that. If you need to intercept multiple controller invocations, use an mvc-interceptor. If you really need to use an aspect, you can get the response if it is passed as argument to the intercepted method.

Questions:
Answers:

Can you simply include the request in the method handle?

@RequestMapping(method=Method.GET, value="myUrl")
public String doGet(HttpServletResponse response){//spring will put the response in for you
  ... 
}

Leave a Reply

Your email address will not be published. Required fields are marked *