擁抱 OpenAPI 3:springdoc-openapi 食用指南

概述

使用 springdoc-openapi 可以快速爲 springboot 項目生成規範的 API 文檔,具體使用步驟如下:

依賴配置

pom.xml 加入內容,即可開始使用:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.9</version>
</dependency>

然後在 Config 中配置基本的描述信息,如下:

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI springOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("SpringDoc API Test")
                        .description("SpringDoc Simple Application Test")
                        .version("0.0.1"));
    }

}

接下來在 Controller 中使用註解標記文本,如下:

@RestController(value = "/clients")
@Tag(name = "/clients")
public class ClientsRestController {

    @Operation(summary = "This method is used to get the clients.")
    @GetMapping
    public List<String> getClients() {
        return Arrays.asList("First Client", "Second Client");
    }
}

最後 Application.java 啓動應用後,輸入默認地址:http://localhost:8081/swagger-ui/index.html 即可看到文檔:

image-20220616224457245

在地址 http://localhost:8081/v3/api-docs 目錄中,openAPI 3.0.1 文件,格式如下:

image-20220616224628270

總結

很多從 swagger 2 過來的用戶可能會好奇,爲什麼不使用 springfox 庫來生成 API,我在這裏簡單總結一下

推薦使用 springdoc-openapi 的理由如下:

  • springdoc-openapi 是 spring 官方出品,與 springboot 兼容更好(springfox 兼容有坑)
  • springdoc-openapi 社區更活躍,springfox 已經 2 年沒更新了
  • springdoc-openapi 的註解更接近 OpenAPI 3 規範

綜上所述,我個人還是更加推薦使用 springdoc-openapi 來自動化你項目的 API 文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章