java @Autowired HttpServletResponse

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6984054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:08:46  来源:igfitidea点击:

@Autowired HttpServletResponse

javaspringspring-mvcautowired

提问by Kevin

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.

我正在寻找一种自动装配的方法HttpServletResponse。它不适用于开箱即用的弹簧,但我找到了这个描述。这有效但有点烦人,因为那个 spring 显然有一种机制来使对象请求范围(即HttpServletRequest),这似乎是一个固定在顶部的黑客。

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 HttpServletRequestautowire capable (and excluded HttpServletResponse)?

有没有办法钩入弹簧使用的相同机制HttpServletRequest?并且,知道为什么 Spring 团队决定只使HttpServletRequestautowire 能够(并排除HttpServletResponse)吗?

采纳答案by Bozho

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 @Controllerbeans that provide @RequestMappingmethods which take the request and response as arguments.

也许有一些解决方法,但不是那么明显,因为这不是它的本意。Spring MVC 旨在拥有@Controller提供@RequestMapping将请求和响应作为参数的方法的单例bean 。

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

要注入响应,您需要: - 将响应存储在 a ThreadLocal- 制作一个返回当前响应的工厂 bean

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.

关于您展示的示例代码 -我不确定您是否不需要工厂 bean 返回代理(实现HttpServletResponse),代理又返回当前响应。它变得相当复杂。

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.

但最终 - 你不应该那样做。如果您需要拦截多个控制器调用,请使用 mvc-interceptor。如果你真的需要使用一个方面,你可以得到响应,如果它作为参数传递给被拦截的方法。

回答by John Vint

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
  ... 
}