将HttpServletResponse注入服务层的最佳方法 [英] Best way to inject HttpServletResponse into service layer
问题描述
我知道这可能不是这类问题的最佳设计,只是针对特定要求。
I know it may not be a best design for a question like this but just for specific requirement.
当前应用程序需要 ServletContext
, HttpServletRequest
, HttpServletResponse
进入自定义身份验证提供程序的服务层
。
Current application needs ServletContext
, HttpServletRequest
, HttpServletResponse
in to service layer for a customized authentication provider
.
以下代码显然没有任何特定配置或继承:
Obviously without any specific configuration or inheritance following code:
@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:
我能想到的可能的解决方案:
Possible solutions I can think of:
-
使用过滤器拦截
HttpServletRequest
,但这需要网址格式,否则会拦截所有网址我认为这可能是一个性能问题?
Intercept
HttpServletRequest
with a filter, but that requires an URL pattern, otherwise will intercept all URLs which I think might be a performance concern?
在spring-security中创建一个请求
范围bean。 xml或application-context.xml然后注入当前的身份验证提供程序类,使其能够获取 HttpServletRequest
。但是我觉得这里有什么问题,比如如何启动请求范围bean?
Create a request
scope bean in spring-security.xml or application-context.xml and then inject into current authentication provider class, to make it capable to get the HttpServletRequest
. But I think there is something wrong here, as how to initiate the request scope bean?
然后可能是什么最佳做法?
Then what could be the best practice?
推荐答案
除了作为一个坏主意之外,请求对象只能在请求时生效。由于生命周期的不同,您无法将其注入单例。您可以通过方法参数传递它。
Beyond being a "bad idea" a request object only lives as long as the request. You can't inject it into a singleton due to lifecycle differences. You can pass it in via a method parameter.
与您的请求匹配的最接近的解决方案是在catch all过滤器内创建一个ThreadLocal变量并将其设置在那里并注入该过滤器或本地线程委托给您的服务。我强烈建议你避免这种情况。
The closest solution matching your request is to create a ThreadLocal variable inside a catch all filter and set it there and inject that filter or a delegate to the thread local into your service. I highly suggest you avoid that.
这篇关于将HttpServletResponse注入服务层的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!