在 Spring 控制器中自动装配 HttpServletRequest

Autowiring HttpServletRequest in Spring controller

假设我有一个 Spring 控制器。

@RequestMappin("/path")
public MyController {
}

如前所述,控制器的默认范围是单例。 我知道我可以在 REQUEST 范围 bean 中自动装配请求,但是,如果我尝试自动装配请求,那么

@RequestMappin("/path")
public MyController {
        @Autowired
        private HttpServletRequest request;
    }

它仍然有效,并且对于每个请求,我都会得到适当的请求对象。这是否意味着无论范围是否为请求,自动装配都能正常工作?

您可以在每个网络服务方法中获取 HttpServletRequest 对象。如:

@RequestMapping("/method")
public void method(HttpServletRequest req) {
   // ...
}

如果有效,则意味着 spring 不完全注入 http 请求,而是注入代理。代理委托对当前 http 请求的调用

当 spring 基于 Web 的应用程序启动时,它将注册类型为 ServletRequestServletResponseHttpSessionWebRequest 的 bean 并支持ThreadLocal 变量。因此,无论何时请求以上四种中的一种,实际值将是绑定到当前线程的实际存储的 ThreadLocal 变量。

@Autowired HttpServletRequest的详细实现机制可以在 @Autowired HttpServletRequest

如果你不想使用@Autowired你可以这样得到HttpServletRequest:

HttpServletRequest request = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();