Spring 應用中 Swagger 2.0 遷移 OpenAPI 3.0 詳解:配置、注解與實踐

從 Swagger 2.0 到 OpenAPI 3.0 的升級指南

為什么升級

OpenAPI 3.0提供了更強大的功能、更簡潔的配置和更好的性能,同時保持了與 Swagger 2.0 的基本兼容性。本文將詳細介紹升級的各個步驟,并提供代碼示例。

1. 依賴管理的變化

Swagger 2.0 依賴配置

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version>
</dependency>

OpenAPI 3.0 依賴配置

<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.2.0</version>
</dependency>

關鍵變化:

  • 從多個 springfox 依賴簡化為單一的 springdoc 依賴
  • 自動集成 Swagger UI 和 OpenAPI 規范生成
  • 無需手動管理多個依賴版本

2. 配置類的重構

Swagger 2.0 配置類

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.example.controller")).paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Swagger 2.0 API").description("API documentation using Swagger 2.0").version("1.0.0").build();}
}

OpenAPI 3.0 配置類

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class OpenAPIConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("OpenAPI 3.0 API").description("API documentation using OpenAPI 3.0").version("1.0.0"));}
}

關鍵變化:

  • 移除了 @EnableSwagger2 注解
  • 不再需要手動配置 Docket 和選擇器
  • 使用 OpenAPI 類直接定義 API 元數據
  • 自動掃描控制器和模型,無需指定包路徑

3. 注解系統的升級

控制器注解對比

Swagger 2.0OpenAPI 3.0 替代方案
@Api@Tag
@ApiOperation@Operation
@ApiParam@Parameter
@ApiResponses@Operationresponses 屬性
@ApiIgnore@Parameter(hidden = true)

模型注解對比

Swagger 2.0OpenAPI 3.0 替代方案
@ApiModel@Schema
@ApiModelProperty@Schema

示例:控制器注解升級

// Swagger 2.0 控制器
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api/users")
@Api(value = "User Management API", description = "Operations related to users")
public class UserControllerV2 {@ApiOperation(value = "Retrieve a user by ID", response = User.class)@GetMapping("/{id}")public User getUserById(@ApiParam(value = "User ID", required = true) @PathVariable Long id) {return userService.findById(id);}
}// OpenAPI 3.0 控制器
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api/users")
@Tag(name = "User Management API", description = "Operations related to users")
public class UserControllerV3 {@Operation(summary = "Retrieve a user by ID",description = "Returns a single user identified by the provided ID")@GetMapping("/{id}")public User getUserById(@Parameter(description = "User ID", required = true) @PathVariable Long id) {return userService.findById(id);}
}

4. 數據模型注解的更新

Swagger 2.0 模型定義

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;@ApiModel(description = "Represents a user in the system")
public class User {@ApiModelProperty(value = "Unique identifier for the user", example = "1")private Long id;@ApiModelProperty(value = "User's full name", example = "John Doe")private String name;@ApiModelProperty(value = "User's email address", example = "john@example.com")private String email;
}

OpenAPI 3.0 模型定義

import io.swagger.v3.oas.annotations.media.Schema;public class User {@Schema(description = "Unique identifier for the user", example = "1", required = true)private Long id;@Schema(description = "User's full name", example = "John Doe", minLength = 2)private String name;@Schema(description = "User's email address", example = "john@example.com", format = "email")private String email;
}

增強功能:

  • 支持更豐富的 format 選項(如 email, date, uuid 等)
  • 直接在 @Schema 中定義約束條件(如 minLength, maxLength
  • 更好的與 JSON Schema 集成

5. 安全配置的升級

Swagger 2.0 安全配置

@Bean
public Docket api() {return new Docket(DocumentationType.SWAGGER_2).securitySchemes(Arrays.asList(apiKey())).securityContexts(Arrays.asList(securityContext()));
}private ApiKey apiKey() {return new ApiKey("JWT", "Authorization", "header");
}private SecurityContext securityContext() {return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/api/.*")).build();
}private List<SecurityReference> defaultAuth() {AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
}

OpenAPI 3.0 安全配置

@Bean
public OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("API").version("1.0.0")).components(new Components().addSecuritySchemes("bearerAuth", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))).addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
}

關鍵改進:

  • 簡化的安全方案定義
  • 支持更多安全類型(如 OAuth2、OpenID Connect)
  • 更清晰的安全要求聲明

6. 處理特殊場景

自定義擴展

// Swagger 2.0 自定義擴展
@Bean
public Docket customImplementation() {return new Docket(DocumentationType.SWAGGER_2).extensions(customVendorExtensions());
}private List<VendorExtension> customVendorExtensions() {List<VendorExtension> extensions = new ArrayList<>();VendorExtension<String> extension = new VendorExtension() {@Overridepublic String getName() {return "x-custom-info";}@Overridepublic String getValue() {return "This is a custom extension";}};extensions.add(extension);return extensions;
}// OpenAPI 3.0 自定義擴展
@Bean
public OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("API").version("1.0.0").addExtension("x-custom-info", "This is a custom extension"));
}

分組 API 文檔

// OpenAPI 3.0 分組配置
@Configuration
public class OpenAPIConfig {@Beanpublic GroupedOpenApi userApi() {return GroupedOpenApi.builder().group("users").pathsToMatch("/api/users/**").build();}@Beanpublic GroupedOpenApi productApi() {return GroupedOpenApi.builder().group("products").pathsToMatch("/api/products/**").build();}
}

7. 驗證升級結果

  1. 訪問 Swagger UI
    • 舊路徑:http://localhost:8080/swagger-ui.html(已失效)
    • 新路徑:http://localhost:8080/swagger-ui/index.html

8. 常見問題與解決方案

  1. 依賴沖突

    • 確保移除所有 springfox 相關依賴
    • 使用 Maven 的 dependency:tree 或 Gradle 的 dependencies 命令檢查沖突
  2. UI 無法訪問

    • 確認 springdoc-openapi-starter-webmvc-ui 依賴已正確添加
    • 檢查是否有自定義 Web 配置攔截了 /swagger-ui/** 路徑
  3. 注解不生效

    • 確認使用的是 io.swagger.v3.oas.annotations 包下的注解
    • 檢查類路徑是否存在舊版本注解
  4. 性能問題

    • OpenAPI 3.0 通常比 Swagger 2.0 更快,但大型項目可能需要配置:
      springdoc.api-docs.enabled=true
      springdoc.swagger-ui.enabled=true
      

總結

從 Swagger 2.0 升級到 OpenAPI 3.0 是一個相對直接的過程,主要涉及依賴替換、配置重構和注解更新。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/89359.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/89359.shtml
英文地址,請注明出處:http://en.pswp.cn/web/89359.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

用 Flink CEP 打造實時超時預警:從理論到實戰

目錄 1. Flink CEP 是什么?為什么它能讓你的數據“開口說話”? 2. 超時預警的業務場景:從電商到物聯網 3. Flink CEP 超時機制的核心原理 3.1 模式匹配與時間窗口 3.2 超時事件的處理 3.3 事件時間與水位線 3.4 核心組件一覽 4. 實戰案例:電商訂單超時預警 4.1 準備…

Rocky Linux 9 源碼包安裝php7

Rocky Linux 9 源碼包安裝php7大家好&#xff01;我是星哥。盡管現在 PHP 版本已迭代至 8.x&#xff0c;但有時為了兼容遺留系統或特定應用需求&#xff0c;我們仍需部署特定版本的 PHP。最主要的是之前的項目采用的PHP7.3&#xff0c;未來兼容舊的項目&#xff0c; 今天&#…

uniapp+vue3+鴻蒙系統的開發

前言&#xff1a; uniappvue3鴻蒙系統的開發。 實現效果&#xff1a; 鴻蒙pad端真機測試效果-下面是正常的日志效果 實現步驟&#xff1a; 1、安裝鴻蒙的開發工具&#xff0c;點擊安裝&#xff0c;注意版本不能太舊了 deveco-studio 2、下載下來是個壓縮包&#xff0c;解壓后…

【C++類和對象解密】面向對象編程的核心概念(下)

之前我們了解到構造函數是在對象實例化之時對對象完成初始化工作的一個函數。在我們不寫時&#xff0c;編譯器會自動生成構造函數。構造函數有一些特點&#xff0c;比如&#xff0c;他對內置類型不做處理&#xff0c;對自定義類型的成員會去調用其自身的構造。我們上篇文章還提…

Flutter基礎(前端教程①②-序列幀動畫)

&#x1f9e0; 核心思路總結??徹底繞過 Image組件重建帶來的性能瓶頸??&#xff1a;不再讓 setState重建包含 Image的 Widget 樹&#xff08;這是開銷大、可能導致閃爍的根源&#xff09;&#xff0c;改為使用底層畫布 (Canvas) 直接繪制預先處理好的圖像幀數據。好的&…

Qt添加dmp文件生成及pdb文件

1.Pdb文件生成 下圖先通過構建生成Pdb文件&#xff0c;然后運行程序&#xff0c;通過提前準備的崩潰按鈕使得程序崩潰&#xff0c;生成“dump文件”的演示。 # #添加dmp文件生成及pdb文件生成DEFINES QT_MESSAGELOGCONTEXT DEFINES QT_DEPRECATED_WARNINGS# # 添加DUMP文件…

opencv、torch、torchvision、tensorflow的區別

一、框架定位與核心差異PyTorch動態計算圖&#xff1a;實時構建計算圖支持Python原生控制流&#xff08;如循環/條件&#xff09;&#xff0c;調試便捷。學術主導&#xff1a;2025年工業部署份額24%&#xff0c;適合快速原型開發&#xff08;如無人機自動駕駛、情緒識別&#x…

離散與組合數學 雜記

生成函數 概念 又稱母函數把一個無窮數列 {an}\{a_n\}{an?}&#xff08;默認從 000 項起&#xff09;表示成 G(x)∑i≥0aixiG(x)\displaystyle\sum_{i\ge0} a_ix^iG(x)i≥0∑?ai?xi 的函數形式。例如&#xff1a; ai2ia_i2^iai?2i&#xff1a;G(x)∑i≥02ixiG(x)\display…

學習OpenCV---顯示圖片

學習OpenCV—顯示圖片 最近在學習OpenCV入門&#xff0c;于是記錄一下自己的學習過程。 一、配置環境 第一步 從官方網站中下載OpenCV開源庫。官方下載網站 打開官網后&#xff0c;能看到有很多的版本。我個人下載的是4.11.0版本。點擊圖中的下載 下載完成后&#xff0c;解…

第一次接觸自動化監測,需要付費廠家安裝服務嗎?比人工測量主要區別是啥?

人工檢測是依靠目測檢查或借助于便攜式儀器測量得到的信息&#xff0c;但是隨著整個行業的發展&#xff0c;傳統的人工檢測方法已經不能滿足檢測需求&#xff0c;從人工檢測到自動化監測已是必然趨勢。 a. 從檢測方式看 人工檢測需要耗費大量的精力&#xff0c;從擺放檢測工具到…

VMware Workstation Pro 17下載安裝

注冊賬號 進入下載地址&#xff1a;Free Downloads - Support Portal - Broadcom support portal - https://support.broadcom.com/ 會讓注冊賬號&#xff0c;注冊一個就行 在右上角 下載 地址&#xff1a;Free Downloads - Support Portal - Broadcom support portal - ht…

SpringBoot 3.x集成阿里云OSS:文件上傳 斷點續傳 權限控制

SpringBoot 3.x集成阿里云OSS&#xff1a;文件上傳&#xff0f;斷點續傳&#xff0f;權限控制Spring Boot 3.x 集成阿里云 OSS 終極指南一、環境準備與依賴配置1. 添加阿里云 OSS SDK 依賴2. 配置 OSS 連接參數二、基礎文件上傳服務1. OSS 客戶端配置2. 文件上傳服務三、斷點續…

牛客周賽 Round 100

A小紅的雙排列沒什么好說的 直接 1 1 2 2 3 3 4 4……#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<iostream> #include<bits/stdc.h> #define ll long long using namespace std; int n; int main(){ios::sync_with_stdio(false); …

【Dv3Admin】菜單管理集成阿里巴巴自定義矢量圖標庫

圖標選擇是后臺管理系統中高頻功能。相比用 Element UI、Ant Design 等自帶的 icon 集&#xff0c;阿里巴巴 iconfont.cn 支持上傳和管理自定義圖標&#xff0c;并生成矢量字體&#xff0c;便于統一維護和擴展。 本文目標是支持自定義 iconfont 圖標的展示和選擇&#xff0c;并…

NO.7數據結構樹|線索二叉樹|樹森林二叉樹轉化|樹森林遍歷|并查集|二叉排序樹|平衡二叉樹|哈夫曼樹|哈夫曼編碼

線索二叉樹 線索二叉樹的基本概念 為了解決無法直接找到該結點在某種遍歷序列中的前驅和后繼結點的問題&#xff0c; 出現了線索二叉樹。 一個二叉樹通過如下的方法“穿起來” &#xff1a; 所有原本為空的右(孩子)指針改為指向該節點在某種遍歷序列中的后繼&#xff0c; 所有原…

R語言基礎| 基本圖形繪制(條形圖、堆積圖、分組圖、填充條形圖、均值條形圖)

目錄 一、前言 二、條形圖 1. 簡單的條形圖 2.堆積、分組和填充條形圖(柱狀圖) &#xff08;1&#xff09;堆積圖&#xff0c;對Improved進行堆積&#xff0c;注意position“stack” &#xff08;2&#xff09;分組圖&#xff0c;對Improved進行分組&#xff0c;注意posit…

SegNet:一種用于圖像分割的深度卷積編碼器解碼器架構

教程/講解視頻點擊文末名片1、什么是語義分割&#xff0c;什么是FCN 我們提出了一種新穎且實用的深度全卷積神經網絡架構&#xff0c;用于語義像素級分割&#xff0c;命名為SegNet。 語義分割是指為圖像中的每個像素分配一個類別標簽&#xff08;如道路、天空、汽車&#xff09…

PyTorch 數據加載全攻略:從自定義數據集到模型訓練

目錄 一、為什么需要數據加載器&#xff1f; 二、自定義 Dataset 類 1. 核心方法解析 2. 代碼實現 三、快速上手&#xff1a;TensorDataset 1. 代碼示例 2. 適用場景 四、DataLoader&#xff1a;批量加載數據的利器 1. 核心參數說明 2. 代碼示例 五、實戰&#xff1…

Python--plist文件的讀取

Python練習&#xff1a;讀取Apple Plist文件 Plist文件簡介 ??定義??&#xff1a;Apple公司創建的基于XML結構的文件格式??特點??&#xff1a;采用XML語法組織數據&#xff0c;可存儲鍵值對、數組等結構化信息文件擴展名??&#xff1a;.plist應用場景: ??iOS系統:?…

JAVA幾個注解記錄

在Java中&#xff0c;Data、AllArgsConstructor和NoArgsConstructor是Lombok庫提供的注解&#xff0c;用于自動生成Java類中的樣板代碼&#xff08;如getter、setter、構造函數等&#xff09;&#xff0c;從而減少冗余代碼&#xff0c;提高開發效率。以下是它們的詳細功能和使用…