You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3与Spring Framework 6中如何正确注册Interceptor?

在Spring Boot 3(Spring Framework 6)中正确注册HandlerInterceptor的方式

你的问题核心是配置类未正确实现WebMvcConfigurer接口,导致重写的addInterceptors方法未被Spring MVC识别,另外手动创建InterceptorRegistry Bean的方式本身就是错误的。以下是正确的解决方法:

标准实现方式(推荐)

确保配置类实现WebMvcConfigurer接口,重写addInterceptors方法注册拦截器,和Spring Boot 2的核心写法一致:

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/api/**"); // 按需配置拦截路径
    }
}

如果希望遵循Spring依赖注入规范,也可以先将MyInterceptor注册为Bean,再注入使用:

@Configuration
public class AppConfig implements WebMvcConfigurer {

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

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor())
                .addPathPatterns("/api/**");
    }
}

关于MappedInterceptor的说明

你用MappedInterceptor的方式能生效,是因为Spring会自动识别并注册这种类型的Bean,但这属于特殊场景的用法。常规场景下更推荐使用WebMvcConfigurer的方式,它更便于统一管理多个拦截器的执行顺序、路径匹配规则等配置。

额外排查点

如果按上述方式配置后仍不生效,可检查:

  • 请求路径是否匹配addPathPatterns中设置的规则,比如请求是否以/api开头
  • 是否存在标注@EnableWebMvc的配置类,该注解会禁用Spring Boot的Web自动配置,可能导致拦截器无法生效
  • 确认项目的组件扫描范围是否覆盖了配置类所在的包

内容的提问来源于stack exchange,提问作者RRGT19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:23:10