Spring: 如何将 HttpServletRequest 注入到请求范围的 bean 中?

我想在春天建立一个 请求作用域的 bean

我已经成功地将其设置为每个请求创建一次 bean。现在,它需要访问 HttpServletRequest 对象。

因为每个请求创建一次 bean,所以我认为容器可以很容易地将请求对象注入到我的 bean 中。我该怎么做?

135112 次浏览

Spring 通过类型为 ServletRequestAttributes包装纸对象公开当前的 HttpServletRequest对象(以及当前的 HttpSession对象)。此包装器对象绑定到 ThreadLocal,并通过调用 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:

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.


Spring Javadoc: RequestContextHolder 请求上下文持有者 | < a href = “ http://static.springsource.org/Spring/docs/3.0.x/Javadoc-api/org/springFramework/web/context/request/ServletRequestAttributes.html”rel = “ noReferrer”> ServletRequestAttritribute

请求范围内的 bean 可以与请求对象自动连接。

private @Autowired HttpServletRequest request;

正如建议的 here,你也可以注入 HttpServletRequest作为一个方法参数,例如:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
...
}