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

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

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


Leave a Comment