发布于2026-07-29 阅读(0)
扫一扫,手机访问
在Web开发中,拦截器几乎是绕不开的组件。但在SpringBoot项目里,该怎么配置才能让它生效?这篇文章就来拆解一下。

和普通属性不同,拦截器本身是一个类,所以不能直接在application.properties里配置,得用Ja va 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这个关键点,就不会掉坑里。另外,日志级别调一下,调试时能省不少事。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8