ianhuang筆記THE ADVENTURER'S JOURNAL
知識世界・持續探索中

ADVENTURE JOURNAL · 探索筆記

Spring Boot API 文件:Swagger 2 歷史整合與 OpenAPI 3

任務導覽 TABLE OF CONTENTS

保留 Springfox 2.2.2 情境,補上相容界線、現代 springdoc 替代與驗證方式。

適用:保留原 Spring/Spring Boot 歷史筆記;可重現練習統一採 Spring Boot 3.5.16、JDK 25 與 Maven,使用 jakarta 套件。編譯目標為 Java 25;上線仍需核對依賴及部署環境。

先備:先依 共用 Spring Boot 練習專案 建立 pom.xml 與 NoteApplication,再加入本文檔案。

原版本與限制

原筆記使用springfox-swagger2/springfox-swagger-ui 2.2.2與Spring Boot早期版本,配置Docket、@EnableSwagger2與Swagger2註解。不能直接用於Boot3的jakarta架構,亦不建議為遷就舊庫關閉新版框架功能。Swagger2檔案格式與SwaggerUI產品是不同概念,OpenAPI3不是只改頁面名稱。

若維護原系統,先保留依賴/Boot/Spring版本並核對/v2/api-docs和/swagger-ui.html。原Swagger2Markup → AsciiDoc → HTML/PDF流程還要固定plugin與輸出工具版本,離線產物生成需獨立CI驗證,不能只新增依賴就宣稱完整。

新練習:springdoc

使用共用Boot3.5.16專案,在dependencies加入:

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

新增src/main/java/notes/HelloController.java:

package notes;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
@RestController
public class HelloController {
    @Operation(summary = "取得練習問候")
    @GetMapping("/api/hello")
    public Map<String, String> hello() { return Map.of("message", "campfire"); }
}

操作與確認

執行mvn spring-boot:run。GET /api/hello應回{"message":"campfire"},/v3/api-docs應包含openapi與/api/hello,開/swagger-ui/index.html能看到並呼叫介面。WebFlux專案需對應webflux starter,不混用webmvc與webflux UI依賴。

springdoc2.x對應Boot3、3.x對應Boot4的版本線,安裝前檢視相容表與修補版。前端檔案能開啟不代表契約完整,還需描述錯誤回應、認證、DTO欄位與範例。公開API文件不加入真正token,UI endpoint依部署政策授權。

參考資料

冒險者留言

comments powered by Disqus

搜尋筆記

輸入關鍵字,探索所有筆記。

ESC 關閉 · 搜尋標題、標籤與文章全文