本文介绍了@Autowired HttpServletResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种自动装配 HttpServletResponse 的方法。它不适用于开箱即用的弹簧,但我发现。这有点令人讨厌,因为那个春天显然有一种机制可以让对象请求作用域(即 HttpServletRequest ),这似乎是一个被诅咒的顶层。

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.

有没有办法挂钩spring用于 HttpServletRequest 的机制?并且,任何想法为什么Spring团队决定只使 HttpServletRequest 能够支持autowire(并排除 HttpServletResponse )?

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)?

推荐答案

也许有一些解决方法,但它并不那么明显,因为它不是它的意思。 Spring MVC意味着有单件 @Controller bean,它们提供 @RequestMapping 方法,这些方法将请求和响应作为参数。

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.

如果您需要在其他地方(服务层)进行响应 - 请不要这样做。响应不应超出Web(控制器)层。

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.

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

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

关于我不确定你是否不需要工厂bean来返回代理(实现 HttpServletResponse ),然后返回当前响应。它变得相当复杂。

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.

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

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.

这篇关于@Autowired HttpServletResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:04