【发布时间】:2011-03-20 05:44:05
【问题描述】:
我正在尝试在 Spring 中设置 request-scoped bean。
我已成功设置,因此每个请求都会创建一次 bean。现在,它需要访问 HttpServletRequest 对象。
由于每个请求都会创建一次 bean,我认为容器可以轻松地将请求对象注入到我的 bean 中。我该怎么做?
【问题讨论】:
我正在尝试在 Spring 中设置 request-scoped bean。
我已成功设置,因此每个请求都会创建一次 bean。现在,它需要访问 HttpServletRequest 对象。
由于每个请求都会创建一次 bean,我认为容器可以轻松地将请求对象注入到我的 bean 中。我该怎么做?
【问题讨论】:
Spring 通过 ServletRequestAttributes 类型的 wrapper 对象公开当前的 HttpServletRequest 对象(以及当前的 HttpSession 对象)。这个包装器对象绑定到ThreadLocal,通过调用static方法RequestContextHolder.currentRequestAttributes()获得。
ServletRequestAttributes 提供了方法getRequest() 获取当前请求,getSession() 获取当前会话和其他方法获取存储在两个范围中的属性。以下代码虽然有点难看,但应该可以让您在应用程序的任何位置获取当前请求对象:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
注意RequestContextHolder.currentRequestAttributes()方法返回一个接口,需要类型转换为实现该接口的ServletRequestAttributes。
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
【讨论】:
请求范围的 bean 可以与请求对象自动装配。
private @Autowired HttpServletRequest request;
【讨论】:
按照here 的建议,您也可以将HttpServletRequest 作为方法参数注入,例如:
public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
...
}
【讨论】: