簡介
OpenAPI 提供了標準化的規範,讓開發者能夠以 json 或 yaml 格式來描述 API 規格。
Springdoc OpenAPI 是一個專門為 Spring Boot REST API 自動產生 API 文件的工具,讓你不需要手動寫 Swagger 設定,就能快速生成互動式文件頁面。
參照 OpenAPI Specification(OAS)
加入依賴(Maven)pom.xml
<modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.5.13</version> <relativePath/> </parent> <groupId>com.yudanny</groupId> <artifactId>yumicro</artifactId> <version>0.0.1-SNAPSHOT</version> <name>yumicro</name> <description/> <packaging>pom</packaging> <modules> <module>accounts</module> </modules> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.8.4</version> </dependency>註: 使用Java x與Spring Boot 3.x.x,有時候 SpringDoc 可能需要相容性微調。
@RestController @RequestMapping(path = "/api", produces = { MediaType.APPLICATION_JSON_VALUE }) @AllArgsConstructor @Validated public class AccountsController { private IAccountsService iAccountsService; @Operation(summary = "Create an account") @Tag(name = "Account", description = "Account Management API") @PostMapping("/create") public ResponseEntity<ResponseDto> createAccount(@Valid @RequestBody CustomerDto customerDto) { iAccountsService.createAccount(customerDto); return ResponseEntity .status(HttpStatus.CREATED) .body(new ResponseDto(AccountsConstants.STATUS_201, AccountsConstants.MESSAGE_201)); } . . . }問題
「在多模組專案中,Parent POM 的依賴管理如何正確傳遞到子模組的 Runtime」
http://localhost:8080/swagger-ui/index.html
SpringDoc OpenAPI 配置問題。當你看到 "Failed to load API definition" 時,通常意味著 Swagger UI 頁面雖然跑起來了,但它去抓取後端 v3/api-docs(JSON 定義檔)時失敗了。
可檢查以下幾個點
1.檢查 API Definition 的實際路徑
Swagger UI 預設請求 /v3/api-docs。
在瀏覽器直接輸入: http://localhost:8070/v3/api-docs
如果出現 404: 代表 SpringDoc 沒有成功掃描到你的 Controller。
如果出現 JSON: 代表 Swagger UI 配置的路徑不對。
2.修正application.yml配置
springdoc: swagger-ui: path: /swagger-ui.html api-docs: path: /v3/api-docs3.多模組專案的依賴問題
在多模組架構中,如果在 Parent 定義了 springdoc-openapi-starter-webmvc-ui,確保子模組 accounts 的 pom.xml 確實有繼承到這個依賴。
正常顯示