商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > SpringBoot拦截器怎么配置?手把手教你实现自定义拦截器

SpringBoot拦截器怎么配置?手把手教你实现自定义拦截器

  发布于2026-07-29 阅读(0)

扫一扫,手机访问

SpringBoot添加拦截器

在Web开发中,拦截器几乎是绕不开的组件。但在SpringBoot项目里,该怎么配置才能让它生效?这篇文章就来拆解一下。

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.

简单翻译一下核心意思:

  • 如果你希望保留SpringBoot的默认MVC特性,同时又想自定义一些配置(比如拦截器、格式化器、视图控制器、消息转换器等),那就让一个类实现WebMvcConfigurer,并加上@Configuration注解——但千万不能加@EnableWebMvc
  • 如果想自定义HandlerMappingHandlerAdapterExceptionResolver这些底层组件,可以通过创建一个WebMvcRegistrationsAdapter实例来实现。
  • 如果打算完全接管SpringMVC,不保留SpringBoot的任何默认配置,那就自己写一个配置类,加上@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.propertiesapplication.yml中加一行:

# 设置org.springframework包的日志级别为debug
logging.level.org.springframework=debug

再次运行,你就会看到SpringMVC更详细的内部日志了。

总结

配置拦截器其实就两步:写一个拦截器类,再写一个配置类注册它。只要记住不加@EnableWebMvc这个关键点,就不会掉坑里。另外,日志级别调一下,调试时能省不少事。

本文转载于:https://www.jb51.net/program/3682425wg.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注