Best way to inject HttpServletResponse into servic

2020-07-18 06:37发布

问题:

I know it may not be a best design for a question like this but just for specific requirement.

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;
        .......
}

must throw exception:

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:

  1. Intercept HttpServletRequest with a filter, but that requires an URL pattern, otherwise will intercept all URLs which I think might be a performance concern?

  2. 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?

回答1:

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.

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.



回答2:

Have you tried to implement HttpRequestHandler interface in your authentication provider along with AuthenticationUserDetailsService?