将 HttpServletRequest class 注入服务 class 的风险

Risk of injecting an HttpServletRequest class into a Service class

我将 HttpServletRequest class 注入到 class 中,@Service 注释将 HttpServletRequest class 的实例传递给实用程序 class (AuthorizationUtils)获得授权 header。这是否有任何风险,例如我的 AuthorizationUtils 试图调用下面的方法并且我的服务 class 或 HttpServletRequest class 已经被销毁?

request.getHeader("Authorization")

我会避免这样做(出于架构原因),但是不,没有风险。

将请求传递给单独的线程(或在单独的线程中执行的异步方法)是不正确的。不是因为 class 会是 "destroyed"(不存在),而是因为规范说:

Each request object is valid only within the scope of a servlet’s service method. [...] Containers commonly recycle request objects in order to avoid the performance overhead of request object creation. The developer must be aware that maintaining references to request objects for which startAsync has not been called outside the scope described above is not recommended as it may have indeterminate results.

如果你的服务是同步的,那么当你的服务方法执行时,servlet的service()方法还没有返回,所以没关系。