@ControllerAdvice与Swagger兼容问题:Swagger文档失效排查
解决Swagger与@ControllerAdvice共存的NoSuchMethodError问题
这个错误本质是Spring依赖版本不兼容导致的:ControllerAdviceBean的构造方法在不同Spring版本中签名有变化,而Swagger相关依赖(springdoc/springfox)依赖的Spring版本和你项目中的spring-web版本不匹配,才会抛出这个错误。以下是具体解决步骤:
1. 统一Spring Boot依赖版本
确保项目所有Spring相关依赖都继承自Spring Boot父依赖的版本,避免版本碎片化:
<!-- Maven父依赖示例 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> <!-- 替换为你实际使用的稳定版本 --> <relativePath/> </parent>
Gradle项目则确保依赖管理插件和Spring Boot版本统一:
plugins { id 'org.springframework.boot' version '3.2.0' id 'io.spring.dependency-management' version '1.1.4' }
2. 匹配Swagger依赖与Spring Boot版本
- 如果你用的是Springfox(已停止维护):Spring Boot 2.x最高兼容Springfox 3.0.0,Spring Boot 3.x完全不支持Springfox,必须替换为springdoc-openapi。
- 如果你用的是springdoc-openapi:
- Spring Boot 3.x → 使用springdoc-openapi v2.x版本
- Spring Boot 2.x → 使用springdoc-openapi v1.x版本
示例Maven依赖(Spring Boot 3.x):
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> </dependency>
3. 清理冲突依赖
执行依赖树分析命令,找出重复或版本不一致的spring-web相关依赖:
- Maven:
mvn dependency:tree - Gradle:
./gradlew dependencies
找到版本不匹配的依赖后,在Swagger相关依赖中排除冲突的Spring模块,比如:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </exclusion> </exclusions> </dependency>
4. 简化GlobalExceptionHandler配置
去掉@ControllerAdvice中不必要的属性,保持类的简洁性,避免触发兼容问题:
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public String handleException(Exception e) { return "Error: " + e.getMessage(); } }
5. 验证配置
启动项目后,访问Swagger文档地址(Spring Boot 3.x默认是http://localhost:8080/swagger-ui.html),确认是否正常加载。
内容的提问来源于stack exchange,提问作者Samuel Maciel
相关产品推荐
相关产品推荐

