简体   繁体   English

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

[英]Spring: how do I inject an HttpServletRequest into a request-scoped bean?

I'm trying to set up a request-scoped bean in Spring. 我正在尝试在Spring中设置一个请求范围的bean

I've successfully set it up so the bean is created once per request. 我已成功设置它,因此每次请求都会创建一次bean。 Now, it needs to access the HttpServletRequest object. 现在,它需要访问HttpServletRequest对象。

Since the bean is created once per request, I figure the container can easily inject the request object in my bean. 由于每次请求都会创建一次bean,我认为容器可以很容易地在我的bean中注入请求对象。 How can I do that ? 我怎样才能做到这一点 ?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes . Spring通过ServletRequestAttributes类型的包装器对象公开当前的HttpServletRequest对象(以及当前的HttpSession对象)。 This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes() . 此包装器对象绑定到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. ServletRequestAttributes提供方法getRequest()来获取当前请求, getSession()获取当前会话以及其他方法来获取存储在两个范围中的属性。 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. 请注意, RequestContextHolder.currentRequestAttributes()方法返回一个接口,需要对实现该接口的ServletRequestAttributes进行类型转换。


Spring Javadoc: RequestContextHolder | Spring Javadoc: RequestContextHolder | ServletRequestAttributes ServletRequestAttributes

请求范围的bean可以与请求对象一起自动装配。

private @Autowired HttpServletRequest request;

As suggested here you can also inject the HttpServletRequest as a method param, eg: 如此处所示您还可以将HttpServletRequest注入方法参数,例如:

public MyResponseObject myApiMethod(
  ...
  HttpServletRequest request
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM