前言
SpringDoc 基于 OpenAPI 3 規(guī)范,用于 SpringBoot 項(xiàng)目中 API 文檔的生成和維護(hù)的工具類。
Swagger 一個(gè)開源的工具集,其中包括Swagger Editor、Swagger UI和Swagger Codegen等組件。Swagger工具集使用OpenAPI規(guī)范,可以生成、展示和測(cè)試基于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”) |
OpenAPI規(guī)范(中文版)
@Tag
用于說(shuō)明或定義的標(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
:指定字符串屬性的最大長(zhǎng)度和最小長(zhǎng)度 -
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/json -
schema
:內(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
方法不會(huì)顯示在 API 文檔中
@Hidden
@GetMapping("/users/{id}")
public User getUserById(@PathVariable("id") Long id) {
// ...
}
代碼參考:
使用在實(shí)體類字段中,實(shí)現(xiàn)對(duì)敏感信息或不需要公開的元素進(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
:簡(jiǎn)短描述 -
description
:更詳細(xì)的描述 -
hidden
:是否隱藏 -
tags
:標(biāo)簽,用于分組API -
operationId
:操作的唯一標(biāo)識(shí)符,建議使用唯一且具有描述性的名稱 -
parameters
:指定相關(guān)的請(qǐng)求參數(shù),使用@Parameter
注解來(lái)定義參數(shù)的詳細(xì)屬性。 -
requestBody
:指定請(qǐng)求的內(nèi)容,使用@RequestBody
注解來(lái)指定請(qǐng)求的類型。 -
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 = "請(qǐng)求描述",
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ù)來(lái)源,可選query
、header
、path
或cookie
,默認(rèn)為空,表示忽略-
ParameterIn.QUERY
請(qǐng)求參數(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 請(qǐng)求的注解
-
description
:請(qǐng)求信息的描述 -
content
:請(qǐng)求的內(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.引入庫(kù) 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>
<!--單元測(cè)試-->
<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.啟動(dòng)項(xiàng)目
啟動(dòng)成功,訪問 http://localhost:8080/doc.html
可以查看分組 API,在線測(cè)試API 等功能
三、總結(jié)
使用步驟:
- 導(dǎo)入對(duì)應(yīng)的包
- 編寫配置類(config、yml)
- 在不同的類上,根據(jù)需求,使用不同的注解說(shuō)明方法的要素
其他的就是多看 knife4j
和 springdoc-openapi
的文檔。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-596133.html
參考文檔
[1]:Spring Boot 中使用 SpringFox 整合 Swagger 3(OpenAPI 3)生成 API 文檔
[2]: ChatGPT 3.5文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-596133.html
到了這里,關(guān)于SpringBoot 整合 knfe4j ,使用 OpenAPI3 規(guī)范的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!