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

添加@EnableSwagger2后Spring Boot启动失败,documentationPluginsBootstrapper报错

Spring Boot添加@EnableSwagger2启动空指针问题解决办法

针对添加@EnableSwagger2后项目启动报documentationPluginsBootstrapper空指针的问题,结合你的环境(Java 8、Spring Boot 2.7.14、Swagger 2.9.2)以及之前尝试Spring Boot 3的情况,给出以下解决办法:

一、当前Spring Boot 2.7.14 + Swagger 2.9.2环境的解决方案

1. 开启循环引用允许

Spring Boot 2.6版本开始默认禁用了循环依赖,而Swagger 2的核心组件DocumentationPluginsBootstrapper和其他组件存在循环引用,直接导致初始化时出现空指针。只需在配置文件中开启循环引用允许即可:

  • YAML格式(application.yml):
spring:
  main:
    allow-circular-references: true
  • Properties格式(application.properties):
spring.main.allow-circular-references=true

2. 检查并补全Swagger依赖

确保项目的依赖中包含完整的Swagger 2组件,避免因依赖缺失导致初始化失败。在pom.xml中添加以下完整依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

添加后清理Maven缓存,重新构建项目。

二、Spring Boot 3环境的适配方案

Spring Boot 3不再兼容Springfox出品的Swagger 2/3,因为Springfox已停止维护,且底层依赖的Jakarta EE规范与Spring Boot 3不匹配。此时应该改用官方推荐的SpringDoc OpenAPI(Swagger 3的替代实现):

  1. 移除所有Springfox相关依赖,在pom.xml中添加SpringDoc依赖:
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 该版本适配Spring Boot 3.x -->
</dependency>
  1. 不需要添加@EnableSwagger2注解,直接启动项目,访问http://localhost:你的端口/swagger-ui.html即可查看API文档。

额外注意事项

  • 如果项目集成了Spring Security,需要在配置类中放行Swagger相关路径,避免拦截导致初始化异常或无法访问文档:比如放行/swagger-ui/**、/v2/api-docs(Swagger 2)或/v3/api-docs/**(SpringDoc)等路径。
  • 若修改配置和依赖后仍有问题,清理本地Maven仓库的对应缓存目录(通常是~/.m2/repository/io/springfox或~/.m2/repository/org/springdoc),重新拉取依赖后再构建项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:58:10