Unable to autowire the service inside my authentication filter in Spring

后端 未结 6 2172
无人及你
无人及你 2020-11-29 23:11

I am trying to authenticate user by token, But when i try to auto wire one my services inside the AuthenticationTokenProcessingFilter i get null pointer excepti

6条回答
  •  春和景丽
    2020-11-29 23:19

    You cannot use dependency injection from a filter out of the box. Although you are using GenericFilterBean your Servlet Filter is not managed by spring. As noted by the javadocs

    This generic filter base class has no dependency on the Spring org.springframework.context.ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see org.springframework.web.context.support.WebApplicationContextUtils).

    In plain English we cannot expect spring to inject the service, but we can lazy set it on the first call. E.g.

    public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
        private MyServices service;
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            if(service==null){
                ServletContext servletContext = request.getServletContext();
                WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
                service = webApplicationContext.getBean(MyServices.class);
            }
            your code ...    
        }
    
    }
    

提交回复
热议问题