我正在尝试设置 request-scoped bean在 Spring 。
我已成功设置,因此每个请求都会创建一次 bean。现在,它需要访问 HttpServletRequest 对象。
由于每个请求都会创建一次 bean,我认为容器可以轻松地将请求对象注入(inject)到我的 bean 中。我该怎么做?
最佳答案
Spring 通过 ServletRequestAttributes< 类型的 wrapper 对象公开当前的
。这个包装对象绑定(bind)到ThreadLocal,通过调用HttpServletRequest
对象(以及当前的 HttpSession
对象)/static
方法RequestContextHolder.currentRequestAttributes()
获取。
ServletRequestAttributes
提供方法getRequest()
获取当前请求,getSession()
获取当前 session 等方法获取存储在两个范围中的属性。以下代码虽然有点难看,但应该可以在应用程序中的任何位置为您提供当前请求对象:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
注意RequestContextHolder.currentRequestAttributes()
方法返回一个接口(interface),需要类型转换为实现该接口(interface)的ServletRequestAttributes
。
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
关于java - Spring:如何将 HttpServletRequest 注入(inject)请求范围的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3320674/