我知道这可能不是解决此类问题的最佳设计,但仅针对特定要求。
当前应用程序需要ServletContext
、HttpServletRequest
、HttpServletResponse
到自定义身份验证提供程序
的服务层。
显然没有任何特定的配置或继承以下代码:
@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:
我能想到的可能的解决方案:
使用过滤器拦截
HttpServletRequest
,但这需要 URL 模式,否则会拦截我认为可能会影响性能的所有 URL?在 spring-security.xml 或 application-context.xml 中创建一个
request
scope bean,然后注入(inject)到当前的认证提供者类中,使其能够获取HttpServletRequest
。但是我觉得这里有问题,如何发起request scope bean?
那么最佳实践是什么?
最佳答案
除了是一个“坏主意”之外,请求对象只存在于请求期间。由于生命周期差异,您不能将其注入(inject)单例。您可以通过方法参数将其传入。
最接近您的要求的解决方案是在捕获所有过滤器内创建一个 ThreadLocal 变量并将其设置在那里,然后将该过滤器或委托(delegate)注入(inject)您的服务中的本地线程。我强烈建议您避免这种情况。
关于java - 将 HttpServletResponse 注入(inject)服务层的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025848/