SpringBoot 使用 OpenAPI3 規(guī)范整合 knife4j的詳細(xì)過程
前言
SpringDoc 基于 OpenAPI 3 規(guī)范,用于 SpringBoot 項(xiàng)目中 API 文檔的生成和維護(hù)的工具類。
Swagger 一個(gè)開源的工具集,其中包括Swagger Editor、Swagger UI和Swagger Codegen等組件。Swagger工具集使用OpenAPI規(guī)范,可以生成、展示和測試基于OpenAPI規(guī)范的API文檔,并提供了生成客戶端代碼的功能。
Knife4j 完全遵循了 Swagger2 的使用方式,同時(shí)還使用了 OpenAPI 3 規(guī)范,所以直接使用 Knife4j 就行。
一、OpenAPI 3 常用注解
SpringDoc 里使用的是 Swagger3 的注解,在 io.swagger.v3.oas.annotations
包里
swagger 2 | swagger 3 |
---|---|
@Api | @Tag |
@ApiIgnore | @Parameter(hidden = true) 或 @Operation(hidden = true) 或 @Hidden |
@ApiImplicitParam | @Parameter |
@ApiImplicitParams | @Parameters |
@ApiModel | @Schema |
@ApiModelProperty | @Schema |
@ApiOperation(value = “foo”, notes = “bar”) | @Operation(summary = “foo”, description = “bar”) |
@ApiParam | @Parameter |
@ApiResponse(code = 404, message = “foo”) | @ApiResponse(responseCode = “404”, description = “foo”) |
@Tag
用于說明或定義的標(biāo)簽。
部分參數(shù):
name
:名稱description
:描述
@Schema
用于描述實(shí)體類屬性的描述、示例、驗(yàn)證規(guī)則等,比如 POJO 類及屬性。
部分參數(shù):
- name:名稱
- title:標(biāo)題
- description:描述
- example:示例值
- required:是否為必須
- format:屬性的格式。如 @Schema(format = "email")
- maxLength 、 minLength:指定字符串屬性的最大長度和最小長度
- maximum 、 minimum:指定數(shù)值屬性的最大值和最小值
- pattern:指定屬性的正則表達(dá)式模式
- type: 數(shù)據(jù)類型(integer,long,float,double,string,byte,binary,boolean,date,dateTime,password),必須是字符串。如 @Schema=(type="integer")
- implementation :具體的實(shí)現(xiàn)類,可以是類本身,也可以是父類或?qū)崿F(xiàn)的接口
@Content
內(nèi)容注解。
部分參數(shù):
mediaType
:內(nèi)容的類型。比如:application/jsonschema
:內(nèi)容的模型定義,使用 @Schema 注解指定模型的相關(guān)信息。
代碼示例
@RequestBody(content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))) @PostMapping("/users") public void createUser(User user) { // ... }
@Hidden
某個(gè)元素(API 操作、實(shí)體類屬性等)是否在 API 文檔中隱藏。
如,getUserById
方法不會顯示在 API 文檔中
@Hidden @GetMapping("/users/{id}") public User getUserById(@PathVariable("id") Long id) { // ... }
代碼參考:
使用在實(shí)體類字段中,實(shí)現(xiàn)對敏感信息或不需要公開的元素進(jìn)行隱藏。如:用戶密碼字段
@Schema(description = "用戶") public class User { @Schema(description = "用戶id") private Long id; @Schema(description = "用戶名") private String name; @Hidden @Schema(description = "用戶密碼") private String password; // ... }
@Operation
描述 API 操作的元數(shù)據(jù)信息。常用于 controller 上
部分參數(shù):
summary
:簡短描述description
:更詳細(xì)的描述hidden
:是否隱藏tags
:標(biāo)簽,用于分組APIoperationId
:操作的唯一標(biāo)識符,建議使用唯一且具有描述性的名稱parameters
:指定相關(guān)的請求參數(shù),使用@Parameter
注解來定義參數(shù)的詳細(xì)屬性。requestBody
:指定請求的內(nèi)容,使用@RequestBody
注解來指定請求的類型。responses
:指定操作的返回內(nèi)容,使用@ApiResponse
注解定義返回值的詳細(xì)屬性。
代碼參考:
@Operation( summary = "操作摘要", description = "操作的詳細(xì)描述", operationId = "operationId", tags = "tag1", parameters = { @Parameter(name = "param1", description = "參數(shù)1", required = true), @Parameter(name = "param2", description = "參數(shù)2", required = false) }, requestBody = @RequestBody( description = "請求描述", required = true, content = @Content( mediaType = "application/json", schema = @Schema(implementation = RequestBodyModel.class) ) ), responses = { @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseModel.class))), @ApiResponse(responseCode = "400", description = "錯(cuò)誤", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseModel.class))) } ) @Tag(name = "標(biāo)簽1") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseModel.class))), @ApiResponse(responseCode = "400", description = "錯(cuò)誤", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseModel.class))) }) public void yourOperation() { // 邏輯 }
@Parameter
用于描述 API 操作中的參數(shù)
部分參數(shù):
- name : 指定的參數(shù)名
- in:參數(shù)來源,可選 query、header、path 或 cookie,默認(rèn)為空,表示忽略
- ParameterIn.QUERY 請求參數(shù)
- ParameterIn.PATH 路徑參數(shù)
- ParameterIn.HEADER header參數(shù)
- ParameterIn.COOKIE cookie 參數(shù)
- description:參數(shù)描述
- required:是否必填,默認(rèn)為 false
- schema :參數(shù)的數(shù)據(jù)類型。如 schema = @Schema(type = "string")
代碼參考:
@Operation(summary = "根據(jù)用戶名查詢用戶列表") @GetMapping("/query/{username}") public List<User> queryUserByName(@Parameter(name = "username", in = ParameterIn.PATH, description = "用戶名", required = true) @PathVariable("username") String userName) { return new ArrayList<>(); }
@Parameters
包含多個(gè) @Parameter
注解,指定多個(gè)參數(shù)。
代碼參考:
包含了 param1 和 param2 兩個(gè)參數(shù)
@Parameters({ @Parameter( name = "param1", description = "Parameter 1 description", required = true, in = ParameterIn.PATH, schema = @Schema(type = "string") ), @Parameter( name = "param2", description = "Parameter 2 description", required = true, in = ParameterIn.QUERY, schema = @Schema(type = "integer") ) })
@RequestBody
API 請求的注解
description
:請求信息的描述content
:請求的內(nèi)容required
:是否必須
@ApiResponse
API 的響應(yīng)信息。
部分參數(shù):
responseCode
:響應(yīng)的 HTTP 狀態(tài)碼description
:響應(yīng)信息的描述content
:響應(yīng)的內(nèi)容
代碼參考:
@ApiResponse(responseCode = "200", description = "查詢成功", content = @Content(schema = @Schema(implementation = User.class))) @ApiResponse(responseCode = "404", description = "查詢失敗") @GetMapping("/users/{id}") public ResponseEntity<User> getUserById(@PathVariable("id") Long id) { // ... }
二、項(xiàng)目搭建
1.引入庫 pom.xml
導(dǎo)入 SpringBoot、Knife4j 的相關(guān)包
<properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <knife4j.version>4.1.0</knife4j.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.12</version> <relativePath/> </parent> <dependencies> <!--web 模塊--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 熱部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--單元測試--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- knife4j-openapi3 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-spring-boot-starter</artifactId> <version>${knife4j.version}</version> </dependency> </dependencies>
查看 knife4j
的目錄結(jié)構(gòu),發(fā)現(xiàn)已集成 springdoc
和 swagger
2.實(shí)體類、控制器
實(shí)體類
@Tag(name = "用戶", description = "用戶實(shí)體類") @Data public class User { @Schema(name = "用戶id", type = "long") private Long id; @Schema(name = "用戶名", type = "long") private String name; @Schema(name = "密碼", type = "password") private String password; }
控制器
在 controller 下新建 admin、front 兩個(gè)包,用于后面的分組顯示。
目錄結(jié)構(gòu)如下:
其中,UserController 結(jié)構(gòu)如下:
package com.zeroing.controller.admin; import com.zeroing.entity.User; import com.zeroing.service.UserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") @Tag(name = "用戶管理", description = "用戶數(shù)據(jù)增刪改查") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") @Operation( summary = "根據(jù)ID,查詢用戶", parameters = { @Parameter(name = "id", required = true, in = ParameterIn.PATH) }, responses = { @ApiResponse(responseCode = "200",description = "成功",content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "400", description = "錯(cuò)誤", content = @Content(mediaType = "application/json")) } ) public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } }
3.knife4j 配置
可參考 knife4j
和 springdoc-openapi
文檔進(jìn)行個(gè)性化的參數(shù)配置。
knife4j 增強(qiáng)配置
springdoc-openapi 屬性配置
yml 配置
# springdoc-openapi項(xiàng)目配置 springdoc: group-configs: - group: 后端管理接口 packages-to-scan: com.zeroing.controller.admin - group: 前端API接口 packages-to-scan: com.zeroing.controller.front # knife4j的增強(qiáng)配置,不需要增強(qiáng)可以不配 knife4j: enable: true setting: language: zh-CN
配置類
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SwaggerConfig { // 設(shè)置 openapi 基礎(chǔ)參數(shù) @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("SpringBoot API 管理") .contact(new Contact().name("N_007").email("xxxx@163.com").url("https://blog.csdn.net/N_007")) .version("1.0") .description( "SpringBoot 集成 Knife4j 示例") .license(new License().name("Apache 2.0"))); } }
4.啟動項(xiàng)目
啟動成功,訪問 http://localhost:8080/doc.html
可以查看分組 API,在線測試API 等功能
三、總結(jié)
使用步驟:
- 導(dǎo)入對應(yīng)的包
- 編寫配置類(config、yml)
- 在不同的類上,根據(jù)需求,使用不同的注解說明方法的要素
其他的就是多看 knife4j
和 springdoc-openapi
的文檔。
參考文檔
[1]:Spring Boot 中使用 SpringFox 整合 Swagger 3(OpenAPI 3)生成 API 文檔
[2]: ChatGPT 3.5
到此這篇關(guān)于SpringBoot 使用 OpenAPI3 規(guī)范整合 knife4j的文章就介紹到這了,更多相關(guān)SpringBoot 整合 knife4j 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何基于ThreadPoolExecutor創(chuàng)建線程池并操作
這篇文章主要介紹了如何基于ThreadPoolExecutor創(chuàng)建線程池并操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11java 中ThreadLocal本地線程和同步機(jī)制的比較
這篇文章主要介紹了java 中ThreadLocal本地線程和同步機(jī)制的比較的相關(guān)資料,需要的朋友可以參考下2017-03-03Netty分布式pipeline傳播inbound事件源碼分析
這篇文章主要為大家介紹了Netty分布式pipeline傳播inbound事件的源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03Spring MVC中使用Controller如何進(jìn)行重定向
這篇文章主要介紹了Spring MVC中使用Controller如何進(jìn)行重定向操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09SpringBoot集成logback打印彩色日志的代碼實(shí)現(xiàn)
Logback是由log4j創(chuàng)始人設(shè)計(jì)的另一個(gè)開源日志組件,默認(rèn)情況下,Spring?Boot會用Logback來記錄日志,并用INFO級別輸出到控制臺,本文給大家介紹了SpringBoot集成logback打印彩色日志,需要的朋友可以參考下2024-03-03