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

SpringBoot项目addFilterBefore()方法报错的解决咨询

解决Spring Boot 3.2.2中Spring Security addFilterBefore类型不兼容问题

核心原因

项目存在依赖版本冲突和Jakarta EE与Java EE API混淆的问题:

  • Spring Boot 3.x 基于Jakarta EE(使用jakarta.servlet.*包),但手动引入了旧版Spring Security 5.x(依赖javax.servlet.*),导致Filter类型不匹配;
  • 手动添加的javax.servlet-api、tomcat-servlet-api与Spring Boot自带的Servlet API冲突;
  • 旧版JJWT(0.9.1)依赖javax包,不兼容Jakarta环境。

具体修复步骤

1. 清理冲突依赖

修改pom.xml,移除以下依赖:

<!-- 移除手动添加的旧版Spring Security配置,spring-boot-starter-security已包含对应版本 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.7.11</version>
</dependency>

<!-- 移除javax.servlet-api,Spring Boot 3.x使用Jakarta Servlet API -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

<!-- 移除tomcat-servlet-api,spring-boot-starter-web已包含 -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-servlet-api</artifactId>
    <version>10.1.0</version>
</dependency>

2. 更新JJWT依赖到兼容Jakarta的版本

替换旧版JJWT依赖为以下内容(以0.12.5版本为例):

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.12.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.12.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.12.5</version>
    <scope>runtime</scope>
</dependency>

3. 修正Security配置代码

移除addFilterBefore方法中的强制类型转换,Spring Security 6.x中UsernamePasswordAuthenticationFilter和你的JwtAuthenticationFilter都实现了jakarta.servlet.Filter,类型自然匹配:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
        .disable()
        .authorizeHttpRequests()
        .antMatchers(PUBLIC_URLS).permitAll()
        .antMatchers(HttpMethod.GET).permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    // 移除强制类型转换,直接调用即可
    http.addFilterBefore(this.jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

额外说明

  • Spring Boot 3.x不支持Spring Fox 3.0.0,若需要API文档,建议替换为SpringDoc OpenAPI;
  • 执行mvn clean install清理旧依赖并重新构建项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:27:35