spring boot 拦截器HandlerInterceptor 不生效的原因排查

java 复制代码
public class UserInterceptor implements HandlerInterceptor

项目添加一个拦截器,发现未生效

1、排查拦截本身是否注入了springbean 容器

java 复制代码
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

2、排查springboot 项目扫描范围是否包含了拦截器所在目录

3、排查拦截器是否注册成功

两种注册方式相互排斥

如果同时配置一个类继承WebMvcConfigurationSupport和一个类实现

WebMvcConfigurer或者WebMvcConfigurerAdapter,就会导致只有一个生效。解决办法:将这些配置都在一个类中设置

这里全局搜索WebMvcConfigurer

和WebMvcConfigurationSuppor

发现项目中已经有了

bash 复制代码
@Configuration
public class FastJsonConfig extends WebMvcConfigurationSupport 

在这里增添

bash 复制代码
@Override
  public void addInterceptors(InterceptorRegistry registry) {

    List<String> excluded=new ArrayList<>();
    excluded.add("/pc/getUserInfoByCode");
    excluded.add("pc/login");
    registry.addInterceptor(loginInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns(excluded);
    super.addInterceptors(registry);
  }

然后打断点,发现项目启动的时候拦截器注册成功,接下来可以正常拿用户登录信息了

相关推荐
q***07144 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
郝开5 小时前
Spring Boot 2.7.18(最终 2.x 系列版本)8 - 日志:Log4j2 基本概念;Log4j2 多环境日志配置策略
spring boot·单元测试·log4j
q***49865 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
沐浴露z7 小时前
【微服务】基本概念介绍
java·微服务
Z3r4y8 小时前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
Kuo-Teng9 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
Jooou9 小时前
Spring事务实现原理深度解析:从源码到架构全面剖析
java·spring·架构·事务
dreams_dream9 小时前
Flask
后端·python·flask