SpringBoot配置自定义拦截器:定义实现HandlerInterceptor的拦截器类,编写实现WebMvcConfigurer的配置类,重写addInterceptors注册拦截器并指定路径,注意勿加@EnableWebMvc以免关闭自动配置。
在Web开发中,拦截器是几乎绕不开的组件。但在SpringBoot项目中,如何配置才能让它生效?本文就来详细拆解一下。

长期稳定更新的攒劲资源: >>>点此立即查看<<<
与普通属性不同,拦截器本身是一个类,因此不能直接在application.properties中配置,必须通过Java Config方式实现。SpringBoot官方文档对此有明确说明,摘录如下:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
简单翻译核心意思:
WebMvcConfigurer,并添加@Configuration注解——但绝对不能加@EnableWebMvc。HandlerMapping、HandlerAdapter、ExceptionResolver等底层组件,可通过创建WebMvcRegistrationsAdapter实例来实现。@Configuration和@EnableWebMvc两个注解。明确了文档前提后,接下来进入实操环节。
@Component
//继承HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is running!");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle method is running!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion method is running!");
}
}
该拦截器实现了HandlerInterceptor接口,覆盖了三个方法:preHandle(请求处理之前)、postHandle(请求处理之后、视图渲染之前)、afterCompletion(整个请求完成之后)。此处仅简单打印日志,便于验证效果。
@Configuration
//实现`WebMvcConfigurer`,并且添加`@Configuration`注解
public class MvcConfiguration implements WebMvcConfigurer {
//注入定义的拦截器
@Autowired
private HandlerInterceptor myInterceptor;
/**
* 重写接口中的addInterceptors方法,添加自定义拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
/*拦截路径*/ registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
关键点:配置类实现WebMvcConfigurer,重写addInterceptors方法,将拦截器注册进去,并指定拦截路径(这里用/**表示所有请求)。注意不要遗漏@Configuration注解,也一定不要加@EnableWebMvc,否则会关闭SpringBoot的自动配置。
启动项目,访问任意一个接口,控制台输出:
preHandle method is running!
postHandle method is running!
afterCompletion method is running!
拦截器已生效。不过可能发现只有这三行打印,而SpringMVC本身的日志信息并未出现。原因很简单:SpringMVC的日志级别默认是debug,而SpringBoot默认只显示info及以上级别,因此需要手动调整日志配置。
在application.properties或application.yml中添加一行:
# 设置org.springframework包的日志级别为debug logging.level.org.springframework=debug
再次运行,即可看到SpringMVC更详细的内部日志。
配置拦截器实际上只需两步:编写一个拦截器类,再编写一个配置类注册它。只要记住不加@EnableWebMvc这个关键点,就不会踩坑。另外,适当调整日志级别,调试时能省不少功夫。
侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述