gpt4 book ai didi

java - 将 HttpServletRequest 类注入(inject) Service 类的风险

转载 作者:行者123 更新时间:2023-12-01 19:07:42 27 4
gpt4 key购买 nike

我将 HttpServletRequest 类注入(inject)到带有 @Service 注释的类中,将 HttpServletRequest 类的实例传递给实用程序类 (AuthorizationUtils) 以获取授权 header 。这是否存在任何风险,例如我的 AuthorizationUtils 尝试调用下面的方法而我的服务类或 HttpServletRequest 类已被销毁?

request.getHeader("授权")

最佳答案

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

将请求传递给单独的线程(或异步方法,在单独的线程中执行)是不正确的。不是因为该类将被“销毁”(这不存在),而是因为规范说:

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() 方法还没有返回,所以没关系。

关于java - 将 HttpServletRequest 类注入(inject) Service 类的风险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59519637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com