Spring Boot 3.x 整合 Swagger(springdoc-openapi)实现接口文档

本文介绍 Spring Boot 3.x 如何使用 springdoc-openapi 实现 Swagger 接口文档,包括版本兼容表、最简单的配置示例和常见错误解决方案。


1. Spring Boot 3.x 和 springdoc-openapi 版本对应表

Spring Boot 版本 Spring Framework 版本 推荐的 springdoc-openapi 版本
3.0.x / 3.1.x 6.0.x / 6.1.x 2.2.x ~ 2.5.x
3.2.x 6.1.x 2.5.x(最推荐)
3.3.x / 3.4.x 6.2.x 目前 2.5.x 不支持,等待 2.6.x

官方明确提示:springdoc 2.5.x 最高支持到 Spring 6.1.x。Spring Boot 3.3+ / 3.4+ 用 2.5.x 会出错。


2. Maven 依赖示例

(推荐)Spring Boot 3.2.x

确认你的父项目版本,例如:

xml 复制代码
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
</parent>

添加 springdoc 依赖:

xml 复制代码
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version>
</dependency>

(可选)Spring Boot 3.4.x(不稳定)

如果要强行在 3.4.x 用,可以试 SNAPSHOT:

xml 复制代码
<repositories>
  <repository>
    <id>sonatype-snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
  </repository>
</repositories>

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.6.0-SNAPSHOT</version>
</dependency>

注意:不稳定,不建议生产环境使用。


3. 最简单的 Spring Boot + Swagger 配置

以下是一个最小可用的示例项目结构。

主类

java 复制代码
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

示例 Controller

java 复制代码
@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Springdoc OpenAPI!";
    }
}

可选的 Swagger 配置类

java 复制代码
@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("示例 API 文档")
                        .version("v1.0")
                        .description("Spring Boot 3 + Springdoc OpenAPI 实现的接口文档示例")
                        .contact(new Contact().name("开发者").email("example@example.com"))
                        .license(new License().name("Apache 2.0").url("http://springdoc.org"))
                );
    }
}

4. 访问地址

启动后,默认访问:

  • Swagger UI 页面

    复制代码
    http://localhost:8080/swagger-ui/index.html
  • JSON 文档

    复制代码
    http://localhost:8080/v3/api-docs
  • YAML 文档

    复制代码
    http://localhost:8080/v3/api-docs.yaml

注意:路径是 /swagger-ui/index.html,不是老版本的 /swagger-ui.html


5. 常见错误和解决方案

错误:NoSuchMethodError: ControllerAdviceBean

原因:Spring Boot 3.3 / 3.4 用的是 Spring Framework 6.2,springdoc 2.5.x 不支持。

解决方法:

  • 降级到 Spring Boot 3.2.x
  • 或尝试使用 springdoc-openapi 2.6.0-SNAPSHOT

6. 总结

  • Spring Boot 3.0 ~ 3.2 推荐使用 springdoc-openapi 2.5.0,兼容稳定。
  • Spring Boot 3.3 / 3.4 官方2.5.x不支持,需等待2.6.x正式版。
  • 生产环境建议使用兼容的稳定版本组合。

如果需要更多内容(Gradle 版本、WebFlux 配置、多分组文档、认证方案等),欢迎留言讨论。