将HttpServletResponse注入服务层的最佳方法


问题内容

我知道这可能不是针对此类问题的最佳设计,而只是针对特定要求。

目前的应用需求ServletContextHttpServletRequestHttpServletResponse在为服务层customized authentication provider

显然没有以下代码的任何特定配置或继承:

@Component("myAuthenticaionProvider")
public class MyAuthenticaionProvider implements AuthenticationUserDetailsService {
    @Autowired private ServletContext context;
    @Autowired private HttpServletRequest request;
    @Autowired private HttpServletResponse response;
        .......
}

必须抛出异常:

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency:

我能想到的可能解决方案:

  1. 拦截HttpServletRequest过滤器,但需要URL模式,否则将拦截所有我认为可能与性能有关的URL?

  2. request在spring-security.xml或application-context.xml中创建一个作用域bean,然后注入到当前的身份验证提供程序类中,以使其能够获取HttpServletRequest。但是我认为这里有问题,例如如何启动请求范围bean?

那么最佳实践是什么?


问题答案:

除了成为“坏主意”之外,请求对象的生存时间仅与请求一样长。由于生命周期的差异,您无法将其注入单个实例。您可以通过方法参数将其传递。

与您的请求最接近的解决方案是在一个catch
all过滤器内创建一个ThreadLocal变量,然后在其中进行设置,然后将该过滤器或委托给本地线程来注入您的服务。我强烈建议您避免这种情况。