使用 Spring Doc 为 Spring REST API 生成 OpenAPI 3.0 文档
Spring Boot 3 整合 springdoc-openapi
概述
springdoc-openapi 是一个用于自动生成 OpenAPI 3.0 文档的库,它支持与 Spring Boot 无缝集成。通过这个库,你可以轻松地生成和展示 RESTful API 的文档,并且可以使用 Swagger UI 或 ReDoc 进行交互式测试。
环境准备
- Spring Boot 3.x
- Java 17+
- Maven
创建 Spring Boot 项目
首先,创建一个新的 Spring Boot 项目。你可以使用 Spring Initializr 来快速生成项目结构。
添加依赖
在 pom.xml 文件中添加 springdoc-openapi-ui 依赖:
<dependencies><!-- Spring Web 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- springdoc-openapi-starter-webmvc-ui 是一个 Spring Boot Starter,它包含了 springdoc-openapi-ui 及其他必要的依赖,简化了依赖管理和配置 --><dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.6.0</version></dependency><!-- springdoc-openapi-ui 依赖 -->
<!-- <dependency>-->
<!-- <groupId>org.springdoc</groupId>-->
<!-- <artifactId>springdoc-openapi-ui</artifactId>-->
<!-- <version>1.8.0</version>-->
<!-- </dependency>-->
</dependencies>
配置文件
在 application.yml 或 application.properties 中配置 Swagger UI 和 ReDoc 的路径(可选):
springdoc:api-docs:path: /v3/api-docsswagger-ui:path: /swagger-ui.htmlenabled: trueoperationsSorter: methodshow-actuator: true
或者在 application.properties 中:
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.enabled=true
springdoc.swagger-ui.operations-sorter=method
springdoc.show-actuator=true
创建模型类
创建一个简单的模型类 User,并使用 @Schema 注解来描述字段:
package org.springdoc.demo.services.user.model;import io.swagger.v3.oas.annotations.media.Schema;@Schema(name = "User", description = "用户实体")
public class User {@Schema(description = "用户ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)private Long id;@Schema(description = "用户名", example = "john_doe", requiredMode = Schema.RequiredMode.REQUIRED)private String username;@Schema(description = "电子邮件", example = "john.doe@example.com", requiredMode = Schema.RequiredMode.REQUIRED)private String email;public User(Long id, String username, String email) {this.id = id;this.username = username;this.email = email;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}
如何想隐藏模型的某个字段,不生成文档,可以使用@Schema(hidden = true)。
当我们的 model 包含 JSR-303 Bean 验证注解(如 @NotNull、@NotBlank、@Size、@Min 和 @Max)时,springdoc-openapi 库会使用它们为相应的约束生成额外的 schema 文档。
/*** * Copyright 2019-2020 the original author or authors.* ** * Licensed under the Apache License, Version 2.0 (the "License");* * you may not use this file except in compliance with the License.* * You may obtain a copy of the License at* ** * https://www.apache.org/licenses/LICENSE-2.0* ** * Unless required by applicable law or agreed to in writing, software* * distributed under the License is distributed on an "AS IS" BASIS,* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and* * limitations under the License.**/package org.springdoc.demo.services.book.model;import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;/*** The type Book.*/
public class Book {/*** The Id.*/@Schema(hidden = true)private long id;/*** The Title.*/@NotBlank@Size(min = 0, max = 20)private String title;/*** The Author.*/@NotBlank@Size(min = 0, max = 30)private String author;
}
创建 RESTful 控制器
创建一个控制器 UserController,包含两个方法:一个使用 OpenAPI 注解,另一个不使用。
我们使用 @Operation 和 @ApiResponses 对 controller 的 /api/user/{id} 端点进行注解。 其实不使用
@Operation 和 @ApiResponses,也会生成文档,只是信息少一些。
package org.springdoc.demo.services.user.controller;import org.springdoc.demo.services.user.model.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 org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/api/user")
public class UserController {private final Map<Long, User> userMap = new HashMap<>();public UserController() {// 初始化一些示例数据userMap.put(1L, new User(1L, "john_doe", "john.doe@example.com"));userMap.put(2L, new User(2L, "jane_doe", "jane.doe@example.com"));}@Operation(summary = "获取用户信息",description = "根据用户ID获取用户信息",responses = {@ApiResponse(responseCode = "200",description = "成功",content = @Content(mediaType = "application/json",schema = @Schema(implementation = User.class))),@ApiResponse(responseCode = "404",description = "未找到用户")})@GetMapping("/{id}")public ResponseEntity<User> getUserById(@PathVariable @Parameter(description = "用户ID") Long id) {User user = userMap.get(id);if (user != null) {return ResponseEntity.ok(user);} else {return ResponseEntity.notFound().build();}}@GetMapping("/{id}/no-annotations")public ResponseEntity<User> getUserByIdNoAnnotations(@PathVariable Long id) {User user = userMap.get(id);if (user != null) {return ResponseEntity.ok(user);} else {return ResponseEntity.notFound().build();}}
}
自定义全局配置
如果你需要自定义全局的 OpenAPI 文档信息,可以创建一个配置类 OpenApiConfig:
package com.example.demo.config;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 OpenApiConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("示例 API 文档").version("1.0").description("这是一个示例 API 文档,用于演示如何整合 springdoc-openapi。").contact(new Contact().name("你的名字").email("your.email@example.com").url("https://example.com")).license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0")));}
}
启动应用
创建一个 Spring Boot 应用程序的主类:
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
访问 Swagger UI
启动应用程序后,你可以通过以下 URL 访问 Swagger UI:
http://localhost:8080/swagger-ui.html
在 Swagger UI 页面中,你可以看到生成的 API 文档,并且可以进行交互式测试。
配置分组
可以在通过配置 application.yml 来设置分组
springdoc:api-docs:version: openapi_3_1path: /v3/api-docsversion: '@springdoc.version@'swagger-ui:path: /swagger-ui.htmlenabled: trueoperationsSorter: methoduse-root-path: true#包扫描路径
# packages-to-scan: com.ruoyi.tenant.controllergroup-configs:- group: user#按包路径匹配packagesToScan: org.springdoc.demo.services.user- group: book#按路径匹配pathsToMatch: /api/book/**#按包路径匹配packagesToScan: org.springdoc.demo.services.book
也可以在配置类里配置
package org.springdoc.demo.services.config;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.springdoc.core.models.GroupedOpenApi;
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("示例 API 文档").version("1.0").description("这是一个示例 API 文档,用于演示如何整合 springdoc-openapi。").contact(new Contact().name("你的名字").email("your.email@example.com").url("https://example.com")).license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0")));}@Beanpublic GroupedOpenApi userApi() {return GroupedOpenApi.builder().group("user")
// .packagesToScan("org.springdoc.demo.services.user").pathsToMatch("/api/user/**").build();}@Beanpublic GroupedOpenApi bookpi() {return GroupedOpenApi.builder().group("book").pathsToMatch("/api/book/**")
// .packagesToScan("org.springdoc.demo.services.book").build();}}
两个方法选择一个就可以了。
总结
通过以上步骤,你已经成功地在 Spring Boot 3 项目中集成了 springdoc-openapi,并生成了 OpenAPI 3.0 文档。你可以根据需要进一步扩展和定制文档,以满足项目的具体需求。
推荐使用 springdoc-openapi 的理由如下:
- springdoc-openapi 是 spring 官方出品,与 springboot 兼容更好(springfox 兼容有坑)
- springdoc-openapi 社区更活跃,springfox 已经 2 年没更新了 springdoc-o
- penapi 的注解更接近 OpenAPI 3 规范
代码仓库:https://github.com/kuankuanba/springdoc-demo.git
相关文章:
使用 Spring Doc 为 Spring REST API 生成 OpenAPI 3.0 文档
Spring Boot 3 整合 springdoc-openapi 概述 springdoc-openapi 是一个用于自动生成 OpenAPI 3.0 文档的库,它支持与 Spring Boot 无缝集成。通过这个库,你可以轻松地生成和展示 RESTful API 的文档,并且可以使用 Swagger UI 或 ReDoc 进行…...
ssm基于ssm框架的滁艺咖啡在线销售系统+vue
系统包含:源码论文 所用技术:SpringBootVueSSMMybatisMysql 免费提供给大家参考或者学习,获取源码请私聊我 需要定制请私聊 目 录 第1章 绪论 1 1.1选题动因 1 1.2目的和意义 1 1.3论文结构安排 2 第2章 开发环境与技术 3 2.1 MYSQ…...
微信小程序 - 动画(Animation)执行过程 / 实现过程 / 实现方式
前言 因官方文档描述不清晰,本文主要介绍微信小程序动画 实现过程 / 实现方式。 实现过程 推荐你对照 官方文档 来看本文章,这样更有利于理解。 简单来说,整个动画实现过程就三步: 创建一个动画实例 animation。调用实例的方法来描述动画。最后通过动画实例的 export 方法…...
【Linux】nohup 命令
【Linux】nohup 命令 1. 语法格式2. 实例3. 查找后台进程 nohup 英文全称 no hang up(不挂起),用于在系统后台不挂断地运行命令,退出终端不会影响程序的运行。 nohup 命令,在默认情况下(非重定向时&#x…...
CSS、Less、Scss
CSS、Less和SCSS都是用于描述网页外观的样式表语言,但它们各自具有不同的特点和功能。以下是对这三者的详细阐述及区别对比: 详细阐述 CSS(Cascading Style Sheets) 定义:CSS是一种用来表现HTML或XML等文件样式的计算机…...
[笔记] ffmpeg docker编译环境搭建
文章目录 环境参考dockerfile 文件步骤常见问题docker 构建镜像出现 INTERNAL_ERROR 失败? 总结 环境 docker 环境 系统centos 7.9 (无所谓了 你用docker编译就无所谓系统了) ffmpeg3.3 参考 https://blog.csdn.net/jiedichina/article/details/71438112 dockerfile 文件 …...
基于SSM的心理咨询管理管理系统(含源码+sql+视频导入教程+文档+PPT)
👉文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1 、功能描述 基于SSM的心理咨询管理管理系统拥有三个角色:学生用户、咨询师、管理员 管理员:学生管理、咨询师管理、文档信息管理、预约信息管理、测试题目管理、测试信息管理…...
南开大学《2023年+2022年810自动控制原理真题》 (完整版)
本文内容,全部选自自动化考研联盟的:《南开大学810自控考研资料》的真题篇。后续会持续更新更多学校,更多年份的真题,记得关注哦~ 目录 2023年真题 2022年真题 Part1:2023年2022年完整版真题 2023年真题 2022年真题…...
【算法】Kruskal最小生成树算法
目录 一、最小生成树 二、Kruskal算法求最小生成树 三、代码 一、最小生成树 什么是最小生成树? 对于一个n个节点的带权图,从中选出n-1条边(保持每个节点的联通)构成一棵树(不能带环),使得…...
Pocket通常指的是一种特定的凹形或凹槽
在几何和计算机辅助设计(CAD)中,“Pocket”通常指的是一种特定的凹形或凹槽,用于表示在物体表面上挖出的区域。其主要特点包括: 凹形区域:Pocket 是一个在三维模型中内凹的区域,通常从物体的表面…...
Cesium基础-(Entity)-(Billboard)
里边包含Vue、React框架代码 2、Billboard 广告牌 Cesium中的Billboard是一种用于在3D场景中添加图像标签的简单方式。Billboard提供了一种方法来显示定向的2D图像,这些图像通常用于表示简单的标记、符号或图标。以下是对Billboard的详细解读: 1. Billboard的定义和特性 B…...
从0到1,解读安卓ASO优化!
大家好,我是互金行业的一名ASO运营专员,目前是负责我们两个APP的ASO方面的维护,今天分享的内容主要是关于安卓ASO优化方案。 大致内容分为三块: 首先我要讲一下ASO是什么;接下来就是安卓的渠道的选择,安卓…...
go语言中流程控制语句
Go语言中的流程控制语句包括条件判断、循环和分支控制。以下是详细介绍: 1. 条件判断语句 if 语句 Go语言的 if 语句与其他语言类似,支持基本的条件判断。 if 条件 {// 执行代码 }if-else 语句: if 条件 {// 执行代码 } else {// 执行代码…...
k8s 部署 emqx
安装cert-manager 使用Helm安装 helm repo add jetstack https://charts.jetstack.io helm repo update helm upgrade --install cert-manager jetstack/cert-manager \--namespace cert-manager \--create-namespace \--set installCRDstrue如果通过helm命令安装失败&#x…...
CSS.导入方式
1.内部样式 在head的style里面定义如 <style>p1{color: brown;}</style> 2.内联样式 直接在标签的里面定义如 <p2 style"color: blue;">这是用了内联样式,蓝色</p2><br> 3.外部样式表 在css文件夹里面构建一个css文件…...
Linux之nfs服务器和dns服务器
NFS服务器 NFS(Network File System,网络文件系统),NFS服务器可以让PC将网络中的NFS服务器共享的目录挂载到本地端的文件系统中,而在本地端的系统 中看来,那个远程主机的目录就好像是自己的一个磁盘分区一样。 注&am…...
大模型系列——AlphaZero/强化学习/MCTS
AlphaGo Zero无需任何人类历史棋谱,仅使用深度强化学习,从零开始训练三天的成就已远远超过了人类数千年积累的围棋知识。 1、围棋知识 (1)如何简单理解围棋知识 (2)数子法分胜负:https://zhu…...
原生js实现拖拽上传(拖拽时高亮上传区域)
文章目录 drop相关事件说明-MDN演示代码(.html) drop相关事件说明-MDN 演示 代码(.html) <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"…...
python道格拉斯算法的实现
废话不多说 直接开干 需要用到模块 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple math #对浮点数的数学运算函数 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple shapely #提供几何形状的操作和分析,如交集、并集、差集等 pip install -i …...
STM32的hal库中,后缀带ex和不带的有什么区别
在STM32的HAL(硬件抽象层)库中,后缀带“ex”和不带“ex”的文件及其包含的内容存在显著的区别。这些区别主要体现在功能扩展性、使用场景以及API的层次上。 一、功能扩展性 不带“ex”后缀的文件: 这些文件通常包含标准的、核心…...
使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式
一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明:假设每台服务器已…...
蓝桥杯 2024 15届国赛 A组 儿童节快乐
P10576 [蓝桥杯 2024 国 A] 儿童节快乐 题目描述 五彩斑斓的气球在蓝天下悠然飘荡,轻快的音乐在耳边持续回荡,小朋友们手牵着手一同畅快欢笑。在这样一片安乐祥和的氛围下,六一来了。 今天是六一儿童节,小蓝老师为了让大家在节…...
定时器任务——若依源码分析
分析util包下面的工具类schedule utils: ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类,封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz,先构建任务的 JobD…...
C++.OpenGL (10/64)基础光照(Basic Lighting)
基础光照(Basic Lighting) 冯氏光照模型(Phong Lighting Model) #mermaid-svg-GLdskXwWINxNGHso {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-GLdskXwWINxNGHso .error-icon{fill:#552222;}#mermaid-svg-GLd…...
大模型多显卡多服务器并行计算方法与实践指南
一、分布式训练概述 大规模语言模型的训练通常需要分布式计算技术,以解决单机资源不足的问题。分布式训练主要分为两种模式: 数据并行:将数据分片到不同设备,每个设备拥有完整的模型副本 模型并行:将模型分割到不同设备,每个设备处理部分模型计算 现代大模型训练通常结合…...
Device Mapper 机制
Device Mapper 机制详解 Device Mapper(简称 DM)是 Linux 内核中的一套通用块设备映射框架,为 LVM、加密磁盘、RAID 等提供底层支持。本文将详细介绍 Device Mapper 的原理、实现、内核配置、常用工具、操作测试流程,并配以详细的…...
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
最近需要在离线机器上运行软件,所以得把软件用docker打包起来,大部分功能都没问题,出了一个奇怪的事情。同样的代码,在本机上用vscode可以运行起来,但是打包之后在docker里出现了问题。使用的是dialog组件,…...
关键领域软件测试的突围之路:如何破解安全与效率的平衡难题
在数字化浪潮席卷全球的今天,软件系统已成为国家关键领域的核心战斗力。不同于普通商业软件,这些承载着国家安全使命的软件系统面临着前所未有的质量挑战——如何在确保绝对安全的前提下,实现高效测试与快速迭代?这一命题正考验着…...
C# 表达式和运算符(求值顺序)
求值顺序 表达式可以由许多嵌套的子表达式构成。子表达式的求值顺序可以使表达式的最终值发生 变化。 例如,已知表达式3*52,依照子表达式的求值顺序,有两种可能的结果,如图9-3所示。 如果乘法先执行,结果是17。如果5…...
Qt 事件处理中 return 的深入解析
Qt 事件处理中 return 的深入解析 在 Qt 事件处理中,return 语句的使用是另一个关键概念,它与 event->accept()/event->ignore() 密切相关但作用不同。让我们详细分析一下它们之间的关系和工作原理。 核心区别:不同层级的事件处理 方…...
