Unable to autowire the service inside my authentication filter in Spring

后端 未结 6 2173
无人及你
无人及你 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:39

    I am late to the party but this solution worked for me.

    Add a ContextLoaderListener in web.xml. applicationContext can have dependency beans.

    
        org.springframework.web.context.ContextLoaderListener
    
    
        contextConfigLocation
        /WEB-INF/applicationContext.xml
    
    

    Then add in MyFilter SpringBeanAutowiringSupport processInjectionBasedOnServletContext which will add the webapplicationcontext into the filter which will add all the dependencies.

    @Component
    public class MyFilter implements Filter {
    
        @Autowired
        @Qualifier("userSessionServiceImpl")
        private UserSessionService userSessionServiceImpl;
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain 
        chain) throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) req;
            if (userSessionServiceImpl == null) {
                ServletContext context = httpRequest.getSession().getServletContext();
            SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, context);
        }
    
           .... (for brevity)
        }
    

    }

提交回复
热议问题