亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細(xì)過程

 更新時(shí)間:2024年07月19日 11:14:48   作者:Micro麥可樂  
SpringDoc OpenAPI 是一個(gè)強(qiáng)大的工具,能夠幫助我們輕松生成 OpenAPI 3.0 規(guī)范的文檔,并提供交互式的 Swagger UI 界面,所以本文給大家介紹了SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細(xì)過程,需要的朋友可以參考下

1、前言

在我們?nèi)粘i_發(fā)過程中,維護(hù)良好的 API 文檔對于團(tuán)隊(duì)協(xié)作和開發(fā)效率至關(guān)重要。SpringDoc OpenAPI 是一個(gè)強(qiáng)大的工具,能夠幫助我們輕松生成 OpenAPI 3.0 規(guī)范的文檔,并提供交互式的 Swagger UI 界面。

本文跟著博主一起來學(xué)習(xí)如何在 Spring Boot 3 項(xiàng)目中整合 SpringDoc OpenAPI,生成在線接口文檔

2、SpringDoc OpenAPI版本介紹

目前 SpringDoc OpenAPI 有兩個(gè)版本 1.x 以及 2.x , 以下是版本對應(yīng)的支持:

Springdoc OpenAPI 1.x:支持 JDK 8 及以上版本(Spring Boot 2.x and 1.x.)
Springdoc OpenAPI 2.x:最新版本要求 JDK 11 及以上(Spring Boot 3.x)

下表描述了兩個(gè)版本主要模塊的更改:

springdoc-openapi-v1springdoc-openapi-v2描述
springdoc-openapi-commonspringdoc-openapi-starter-common包含基礎(chǔ)springdoc-openapi功能
springdoc-openapi-data-restspringdoc-openapi-starter-commonSpringData Rest 支持
springdoc-openapi-groovyspringdoc-openapi-starter-commonGroovy支持
springdoc-openapi-hateoasspringdoc-openapi-starter-commonSpring Hateoas 支持
springdoc-openapi-javadocspringdoc-openapi-starter-commonJavadoc支持
springdoc-openapi-kotlinspringdoc-openapi-starter-commonkotlin支持
springdoc-openapi-securityspringdoc-openapi-starter-commonSpring Security支持
springdoc-openapi-webmvc-corespringdoc-openapi-starter-webmvc-apiSpring WebMvc支持
springdoc-openapi-webflux-corespringdoc-openapi-starter-webflux-apiSpring WebFlux支持
springdoc-openapi-uispringdoc-openapi-starter-webmvc-ui在Spring WebMvc上下文中使用Swagger-UI
springdoc-openapi-webflux-uispringdoc-openapi-starter-webflux-ui在Spring WebFlux上下文中使用Swagger-UI

確保你使用的 JDK 版本與 springdoc-openapi 的版本相匹配。如果你使用的是 Spring Boot 3,Springdoc OpenAPI 2.x 是推薦的版本,因?yàn)?Spring Boot 3 也要求 JDK 17 及以上

3、項(xiàng)目初始化

配置依賴

創(chuàng)建一個(gè)新的 Spring Boot 3 項(xiàng)目,這里博主選用的JDK版本為JDK17 ,Spring Boot: 3.0.0,在我們的在 pom.xml 文件中添加 Springdoc OpenAPI 的依賴

	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Springdoc OpenAPI Starter -->
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.5.0</version>
   </dependency>

配置 Springdoc OpenAPI

springdoc-openapi 通過自動(dòng)配置大多數(shù)情況下無需額外配置,但如果小伙伴有特定需求,可以在 application.yml 文件中添加配置,如:

springdoc:
  api-docs:
    enabled: true #
    path: /api-docs # 默認(rèn)/v3/api-docs
  swagger-ui:
    path: /swagger-ui.html #自定義swagger-ui HTML文檔路徑

編寫 REST Controller

創(chuàng)建一個(gè)簡單的 REST 控制器,并使用 OpenAPI 注解來描述 API

定義User對象

首先,我們?yōu)?User 類的字段添加注解說明

/**
* description 字段描述
* example 字段返回示例
**/
@Data
public class User {
    @Schema(description = "用戶ID", example = "1")
    private Long id;
    @Schema(description = "用戶姓名", example = "張三")
    private String name;
    @Schema(description = "用戶郵箱", example = "zhansan@qq.com")
    private String email;
}

創(chuàng)建一個(gè)簡單的 REST Controller,并使用 OpenAPI 注解來描述 API

import com.toher.springdoc.bean.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.responses.ApiResponses;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 麥可樂
 * @Date 2024/6/20 11:17 AM
 * @Version 1.0
 */

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Operation(summary = "獲取用戶信息接口", description = "通過用戶ID獲取用戶信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "用戶信息",
                    content = {@Content(mediaType = "application/json",
                    schema = @Schema(implementation = User.class))}),
            @ApiResponse(responseCode = "404", description = "無法獲取用戶信息")
    })
    @GetMapping("/{id}")
    public User getUserById(@Parameter(description = "用戶ID") @PathVariable Long id) {
        //模擬數(shù)據(jù)庫獲取用戶
        User user = new User();
        user.setId(1L);
        user.setName("張三");
        user.setEmail("zhansan@qq.com");
        return user;
    }

    @Operation(summary = "創(chuàng)建用戶接口", description = "創(chuàng)建一個(gè)新用戶并返回帶有用戶id的User對象")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "用戶創(chuàng)建",
                    content = {@Content(mediaType = "application/json",
                    schema = @Schema(implementation = User.class))})
    })
    @PostMapping
    public User createUser(@RequestBody User user) {
        //模擬數(shù)據(jù)庫保存用戶并返回用戶ID主鍵
        user.setId(1L);
        return user;
    }
}

測試查看文檔

最后啟動(dòng)項(xiàng)目訪問查看文檔 http://localhost:端口號/swagger-ui,小伙伴應(yīng)該能夠看到自動(dòng)生成的 API 文檔,并可以在界面中進(jìn)行 API 測試,如下圖:

在這里插入圖片描述

4、如何進(jìn)行文檔分組

很多時(shí)候我們的接口很多,且可能不同的開發(fā)人員分配不同的模塊,如果所有接口都集中在一起,很明顯不利于我們查閱,這里博主介紹一下如何對文檔進(jìn)行分組。

需要實(shí)用一個(gè)配置 group-configs, 如博主的配置

springdoc:
  api-docs:
    enabled: true #
    path: /api-docs # 默認(rèn)/v3/api-docs
  swagger-ui:
    path: /swagger-ui.html
  group-configs: #進(jìn)行文檔分組每個(gè)組配置對應(yīng)的請求路徑以及區(qū)分所在包
    - group: 'user'
      paths-to-match: '/api/users/**'
      packages-to-scan: com.toher.springdoc.user
    - group: 'product'
      paths-to-match: '/api/product/**'
      packages-to-scan: com.toher.springdoc.product

繼續(xù)測試訪問文檔,右上角 Select a definition 查看是否已經(jīng)分組

在這里插入圖片描述

5、更換接口文檔UI

相信很多小伙伴還是不喜歡swagger-ui的文檔,這里博主介紹一個(gè)集 Swagger2OpenAPI3 為一體的增強(qiáng)解決方案 - Knife4j

要使用 Knife4j 非常簡單,只需要引入依賴即可

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

如果你希望開啟 Knife4j 的增強(qiáng),可以在yml配置文件中追加,具體Knife4j增強(qiáng)配置明細(xì),可以查看官方文檔 https://doc.xiaominfo.com/docs/features/enhance 這里就不贅述了

# knife4j的增強(qiáng)配置,不需要增強(qiáng)可以不配
knife4j:
  enable: true
  setting:
    language: zh_cn

重啟我們的 SpringBoot 應(yīng)用訪問 http://localhost:端口號/doc.html 查看

在這里插入圖片描述

6、字段必填如何設(shè)置

相信很多小伙伴在SpringBoot2的時(shí)候?qū)τ谖臋n中一些字段的要求,如:必填,我們可以使用一個(gè)注解屬性 required = true 來說明

	@Schema(description = "用戶姓名", example = "張三" , required = true)
    private String name;

但實(shí)際上在最新版本的 Springdoc OpenAPI 中,@Schema 注解的 required 屬性已經(jīng)被標(biāo)記為過時(shí)。取而代之的是將字段的非空校驗(yàn)放在參數(shù)或方法級別的注解上,結(jié)合 jakarta.validation

Springdoc OpenAPI 3 中,你可以使用 @Parameter@RequestBody 注解來指定字段是否必需,同時(shí)在 @Schema 注解中可以通過指定非空屬性

下面我們來改造一下我們之前的代碼

User對象

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import lombok.Data;

@Data
public class User {
    @Schema(description = "用戶ID", example = "1")
    private Long id;

    @Schema(description = "用戶姓名", example = "張三")
    @NotNull(message = "Name必填")
    private String name;

    @Schema(description = "用戶郵箱", example = "zhansan@qq.com")
    @NotNull(message = "Email必填")
    @Email(message = "郵箱格式不正確")
    private String email;
}

UserController

import com.toher.springdoc.user.bean.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用戶接口")
public class UserController {

    @Operation(summary = "獲取用戶信息接口", description = "通過用戶ID獲取用戶信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "用戶信息",
                    content = {@Content(mediaType = "application/json",
                    schema = @Schema(implementation = User.class))}),
            @ApiResponse(responseCode = "404", description = "無法獲取用戶信息")
    })
    @GetMapping("/{id}")
    public User getUserById(@Parameter(description = "用戶ID") @PathVariable Long id) {
        //模擬數(shù)據(jù)庫獲取用戶
        User user = new User();
        user.setId(1L);
        user.setName("張三");
        user.setEmail("zhansan@qq.com");
        return user;
    }

    @Operation(summary = "創(chuàng)建用戶接口", description = "創(chuàng)建一個(gè)新用戶并返回帶有用戶id的User對象")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "用戶創(chuàng)建",
                    content = {@Content(mediaType = "application/json",
                    schema = @Schema(implementation = User.class))})
    })
    @PostMapping
    public User createUser(@Valid @RequestBody User user) {
        //模擬數(shù)據(jù)庫保存用戶并返回用戶ID主鍵
        user.setId(1L);
        return user;
    }
}

OK,我們還是重啟應(yīng)用觀察文檔說明。是否必填項(xiàng)上已經(jīng)顯示必填

在這里插入圖片描述

7、結(jié)語

通過整合 Spring Boot 3 和 Springdoc OpenAPI,可以非常方便地生成交互式的在線 API 文檔,幫助開發(fā)者和使用者理解和測試 API。這不僅提高了開發(fā)效率,還能保證文檔的及時(shí)更新,保持與實(shí)際代碼的一致性。

以上就是SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細(xì)過程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot3整合SpringDoc OpenAPI的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java中死鎖的原理實(shí)戰(zhàn)分析

    Java中死鎖的原理實(shí)戰(zhàn)分析

    這篇文章主要介紹了Java中死鎖的原理,結(jié)合具體案例形式分析了java死鎖形成的相關(guān)原理,需要的朋友可以參考下
    2019-08-08
  • Springboot集成第三方j(luò)ar快速實(shí)現(xiàn)微信、支付寶等支付場景

    Springboot集成第三方j(luò)ar快速實(shí)現(xiàn)微信、支付寶等支付場景

    這篇文章主要介紹了Springboot集成第三方j(luò)ar快速實(shí)現(xiàn)微信、支付寶等支付場景,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • 解決MyEclipse出現(xiàn)the user operation is waiting的問題

    解決MyEclipse出現(xiàn)the user operation is waiting的問題

    今天做項(xiàng)目的時(shí)候每次修改代碼保存后都會(huì)跳出一個(gè)框框,然后就有兩個(gè)進(jìn)度條,上面寫the user operation is wating...小編去網(wǎng)上查了查解決了這個(gè)問題,下面跟大家分享一下。
    2018-04-04
  • Java中IOException異常解決方法

    Java中IOException異常解決方法

    這篇文章主要給大家介紹了關(guān)于Java中IOException異常解決的相關(guān)資料,IOException是Java中的一個(gè)受檢查異常(Checked?Exception),它是java.io包中定義的異常類之一,需要的朋友可以參考下
    2023-07-07
  • 簡單解析execute和submit有什么區(qū)別

    簡單解析execute和submit有什么區(qū)別

    這篇文章主要介紹了簡單解析execute和submit有什么區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Java11新特性之HttpClient小試牛刀

    Java11新特性之HttpClient小試牛刀

    本文主要研究一下Java11的HttpClient的基本使用。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-09-09
  • Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié)

    Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié)

    這篇文章主要介紹了Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié),多態(tài)是繼封裝、繼承之后,面向?qū)ο蟮牡谌筇匦裕疚闹豢偨Y(jié)了多態(tài)的實(shí)現(xiàn)原理,需要的朋友可以參考一下
    2022-06-06
  • Java并發(fā)編程之常用的輔助類詳解

    Java并發(fā)編程之常用的輔助類詳解

    這篇文章主要給大家介紹了關(guān)于Java并發(fā)編程之常用的輔助類的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • gson對象序列化的示例

    gson對象序列化的示例

    本文介紹如何將Java對象序列化為Json文件,然后讀取該Json文件讀取回Java對象。在下面的示例中,我們創(chuàng)建了一個(gè)Student類。然后生成一個(gè)student.json文件,該文件將具有Student對象的json數(shù)據(jù)。
    2020-11-11
  • Java使用Collections工具類對List集合進(jìn)行排序

    Java使用Collections工具類對List集合進(jìn)行排序

    這篇文章主要介紹了Java使用Collections工具類對List集合進(jìn)行排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10

最新評論