国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot 整合 knfe4j ,使用 OpenAPI3 規(guī)范

這篇具有很好參考價(jià)值的文章主要介紹了SpringBoot 整合 knfe4j ,使用 OpenAPI3 規(guī)范。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。


前言

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)源,可選 queryheader、pathcookie,默認(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)已集成 springdocswagger
knife4j openapi,環(huán)境搭建,spring boot,java,后端,oneapi

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)如下:
knife4j openapi,環(huán)境搭建,spring boot,java,后端,oneapi
其中,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 配置

可參考 knife4jspringdoc-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 等功能
knife4j openapi,環(huán)境搭建,spring boot,java,后端,oneapi


三、總結(jié)

使用步驟:

  • 導(dǎo)入對(duì)應(yīng)的包
  • 編寫配置類(config、yml)
  • 在不同的類上,根據(jù)需求,使用不同的注解說(shuō)明方法的要素

其他的就是多看 knife4jspringdoc-openapi 的文檔。

參考文檔

[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)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【微信公眾號(hào)】15、SpringBoot整合WxJava實(shí)現(xiàn)openApi管理

    1、清空api的調(diào)用quota 本接口用于清空公眾號(hào)/小程序/第三方平臺(tái)等接口的每日調(diào)用接口次數(shù) 注意事項(xiàng): 如果要清空公眾號(hào)的接口的quota,則需要用公眾號(hào)的access_token;如果要清空小程序的接口的quota,則需要用小程序的access_token;如果要清空第三方平臺(tái)的接口的quota,則需要

    2024年02月16日
    瀏覽(23)
  • springboot整合neo4j-使用原生cypher

    該文的實(shí)現(xiàn)有更簡(jiǎn)單的方式,詳見我的另一篇博客springboot整合neo4j–采用Neo4jClient和Neo4jTemplate方式 Neo4j 提供 JAVA API 以編程方式執(zhí)行所有數(shù)據(jù)庫(kù)操作。它支持三種類型的API: 1、Neo4j 原生的 Java API 原生 Java API 是一種低級(jí)別的純 JAVA API,用于執(zhí)行數(shù)據(jù)庫(kù)操作。 2、Neo4j Cypher Jav

    2024年02月12日
    瀏覽(24)
  • 【微服務(wù)】SpringBoot整合Resilience4j使用詳解

    【微服務(wù)】SpringBoot整合Resilience4j使用詳解

    目錄 一、前言 二、熔斷器出現(xiàn)背景 2.1 幾個(gè)核心概念 2.1.1 熔斷 2.1.2 限流 2.1.3 降級(jí) 2.2 為什么會(huì)出現(xiàn)熔斷器 2.3 斷路器介紹 2.3.1 斷路器原理 三、Resilience4j介紹 3.1 Resilience4j概述 3.1.1 Resilience4j是什么 3.1.2 Resilience4j功能特性 3.2 Resilience4j核心組件 3.2.1 Bulkhead 3.3 Resilience4j狀態(tài)機(jī)

    2024年03月11日
    瀏覽(18)
  • 【微服務(wù)】springboot整合neo4j使用詳解

    在上一篇我們?cè)敿?xì)了解了neo4j的使用,從搭建到相關(guān)的語(yǔ)法操作,本篇緊接著之前的內(nèi)容,來(lái)詳細(xì)聊聊如何在springboot應(yīng)用中集成和使用neo4j。 和很多其他的中間件類似,都提供了類似jpa的方式與springboot進(jìn)行集成,比如大家熟悉的springdata-jpa,操作es的jpa,操作mongo的jpa等,而

    2024年02月08日
    瀏覽(22)
  • Springboot 2.7 集成 Swagger 增強(qiáng)版接口框架 Knife4j 4.3 + springdoc OpenApi 3.0

    Springboot 2.7 集成 Swagger 增強(qiáng)版接口框架 Knife4j 4.3 + springdoc OpenApi 3.0

    Swagger 作為一款服務(wù)端接口文檔自動(dòng)生成框架,早已深入人心,并且在市場(chǎng)上得到了廣泛的應(yīng)用。然而,Swagger 3.0 也就是 OpenApi 3.0 規(guī)范發(fā)布之后便停止了更新維護(hù),出道就是巔峰。Knife4j 作為 Swagger 的增強(qiáng)版,是對(duì) Swagger UI 做了優(yōu)化,同時(shí)還有很多增強(qiáng)的功能。伴隨著 Swagge

    2024年02月08日
    瀏覽(33)
  • springboot整合neo4j-使用原生cypher Java API

    該文的實(shí)現(xiàn)有更簡(jiǎn)單的方式,詳見我的另一篇博客springboot整合neo4j–采用Neo4jClient和Neo4jTemplate方式 Neo4j 提供 JAVA API 以編程方式執(zhí)行所有數(shù)據(jù)庫(kù)操作。它支持三種類型的API: 1、Neo4j 原生的 Java API 原生 Java API 是一種低級(jí)別的純 JAVA API,用于執(zhí)行數(shù)據(jù)庫(kù)操作。 2、Neo4j Cypher Jav

    2024年02月09日
    瀏覽(23)
  • Springboot整合與使用log4j2日志框架【詳解版】

    Springboot整合與使用log4j2日志框架【詳解版】

    Spring Boot默認(rèn)使用LogBack,但是我們沒有看到顯示依賴的jar包,其實(shí)是因?yàn)樗诘膉ar包spring-boot-starter-logging都是作為spring-boot-starter-web或者spring-boot-starter依賴的一部分。 如果這里要使用Log4j2,需要從spring-boot-starter-web中去掉spring-boot-starter-logging依賴,同時(shí)顯示聲明使用Log4j2的依

    2024年02月11日
    瀏覽(29)
  • Springboot使用自帶Logback 與 整合log4j 和 log4j2過(guò)程詳解

    Springboot使用自帶Logback 與 整合log4j 和 log4j2過(guò)程詳解

    1、添加依賴 2、logback-spring.xml配置 3、使用? ?本地日志: 1、添加依賴 2、log4j.properties文件配置 ?3、配置文件中設(shè)置日志 application.yml: 4、使用: 1、添加依賴 2、log4j2.xml配置 3、配置文件中設(shè)置日志 application.yml 4、使用: 注意:如果pom.xml中添加有?spring-boot-starter-test 依賴 必

    2024年01月19日
    瀏覽(58)
  • 圖數(shù)據(jù)庫(kù)_Neo4j和SpringBoot整合使用_實(shí)戰(zhàn)創(chuàng)建明星關(guān)系圖譜---Neo4j圖數(shù)據(jù)庫(kù)工作筆記0010

    2023-09-10 10:37:48 補(bǔ)充 注意:下面是舊版本的語(yǔ)法,如果你發(fā)現(xiàn)@NodeEntity這樣的注解沒有的話可以這樣: 這里就要用@Node 另外如果@StartNode和@EndNode都沒有了,那么說(shuō)明是用法變了. 關(guān)于最新的用法,在官網(wǎng)有明確的說(shuō)明和案例,很有用: 下面給出官網(wǎng)的案例:

    2024年02月12日
    瀏覽(23)
  • 圖數(shù)據(jù)庫(kù)_Neo4j和SpringBoot Data整合使用_實(shí)戰(zhàn)創(chuàng)建明星關(guān)系圖譜---Neo4j圖數(shù)據(jù)庫(kù)工作筆記0010

    2023-09-10 10:37:48 補(bǔ)充 注意:下面是舊版本的語(yǔ)法,如果你發(fā)現(xiàn)@NodeEntity這樣的注解沒有的話可以這樣: 這里就要用@Node 另外如果@StartNode和@EndNode都沒有了,那么說(shuō)明是用法變了. 關(guān)于最新的用法,在官網(wǎng)有明確的說(shuō)明和案例,很有用: 下面給出官網(wǎng)的案例:

    2024年02月09日
    瀏覽(47)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包