Java Spring:如何将 HttpServletRequest 注入请求范围的 bean?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3320674/
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
Spring: how do I inject an HttpServletRequest into a request-scoped bean?
提问by Leonel
I'm trying to set up a request-scoped beanin Spring.
我正在尝试在 Spring 中设置一个请求范围的 bean。
I've successfully set it up so the bean is created once per request. Now, it needs to access the HttpServletRequest object.
我已经成功设置了它,因此每个请求都会创建一次 bean。现在,它需要访问 HttpServletRequest 对象。
Since the bean is created once per request, I figure the container can easily inject the request object in my bean. How can I do that ?
由于每个请求都会创建一次 bean,我认为容器可以轻松地将请求对象注入到我的 bean 中。我怎样才能做到这一点 ?
采纳答案by skaffman
Request-scoped beans can be autowired with the request object.
请求范围的 bean 可以与请求对象自动装配。
private @Autowired HttpServletRequest request;
回答by samitgaur
Spring exposes the current HttpServletRequest
object (as well as the current HttpSession
object) through a wrapperobject of type ServletRequestAttributes
. This wrapper object is bound to ThreadLocal and is obtained by calling the static
method RequestContextHolder.currentRequestAttributes()
.
Spring通过类型为 的包装器对象公开当前HttpServletRequest
对象(以及当前HttpSession
对象)。该包装器对象绑定到 ThreadLocal 并通过调用方法获得。ServletRequestAttributes
static
RequestContextHolder.currentRequestAttributes()
ServletRequestAttributes
provides the method getRequest()
to get the current request, getSession()
to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:
ServletRequestAttributes
提供getRequest()
获取当前请求、getSession()
获取当前会话的方法以及获取存储在两个范围中的属性的其他方法。下面的代码虽然有点难看,但应该能让你在应用程序的任何地方获取当前的请求对象:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Note that the RequestContextHolder.currentRequestAttributes()
method returns an interface and needs to be typecasted to ServletRequestAttributes
that implements the interface.
请注意,该RequestContextHolder.currentRequestAttributes()
方法返回一个接口,需要将其类型转换为ServletRequestAttributes
实现该接口的类型。
Spring Javadoc:RequestContextHolder| ServletRequestAttributes
Spring Javadoc:RequestContextHolder| ServletRequestAttributes