Spring MVC - Interceptor never called

r.rodriguez picture r.rodriguez · Mar 25, 2014 · Viewed 9.9k times · Source

I am trying to configure an interceptor in my application and I am not being able to make it work.

In my application configuration class, I have configured in the following way:

@Configuration
@EnableWebMvc
public class AppContextConfiguration extends WebMvcConfigurerAdapter {
    ...
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }
    ...
}

And the interceptor:

public class MyInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
        Object handler) throws Exception {

        logger.debug("MyInterceptor - PREHANDLE");
    }
}

Does anybody know why is not being invoked?

Answer

Theo picture Theo · Mar 11, 2016

I'm using Spring Boot and was having the same problem where addInterceptors() was being called to register the interceptor, but the interceptor never fired during a request. Yet XML configuration worked no problem.

Basically, you don't need the WebMvcConfigurerAdapter class. You just need to declare an @Bean of type MappedInterceptor:

@Bean
public MappedInterceptor myInterceptor()
{
    return new MappedInterceptor(null, new MyInterceptor());
}