Spring MVC-拦截器从未调用 [英] Spring MVC - Interceptor never called
问题描述
我正在尝试在应用程序中配置拦截器,但无法使其正常工作.
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());
}
...
}
拦截器:
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?
推荐答案
我正在使用Spring Boot,并且遇到相同的问题,即调用addInterceptors()
来注册拦截器,但是该拦截器在请求期间从未触发过.但是XML配置没有问题.
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.
基本上,您不需要WebMvcConfigurerAdapter
类.您只需要声明MappedInterceptor
类型的@Bean
:
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());
}
这篇关于Spring MVC-拦截器从未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!