本文介紹 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
確認你的父項目版本,例如:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.5</version>
</parent>
添加 springdoc 依賴:
<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:
<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 配置
以下是一個最小可用的示例項目結構。
主類
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
示例 Controller
@RestController
@RequestMapping("/api")
public class HelloController {@GetMapping("/hello")public String hello() {return "Hello, Springdoc OpenAPI!";}
}
可選的 Swagger 配置類
@Configuration
public class SwaggerConfig {@Beanpublic 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 配置、多分組文檔、認證方案等),歡迎留言討論。