Unable to autowire the service inside my authentication filter in Spring

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

}

Leave a Comment