使用 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”后缀的文件: 这些文件通常包含标准的、核心…...
web vue 项目 Docker化部署
Web 项目 Docker 化部署详细教程 目录 Web 项目 Docker 化部署概述Dockerfile 详解 构建阶段生产阶段 构建和运行 Docker 镜像 1. Web 项目 Docker 化部署概述 Docker 化部署的主要步骤分为以下几个阶段: 构建阶段(Build Stage):…...

微信小程序 - 手机震动
一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注:文档 https://developers.weixin.qq…...

成都鼎讯硬核科技!雷达目标与干扰模拟器,以卓越性能制胜电磁频谱战
在现代战争中,电磁频谱已成为继陆、海、空、天之后的 “第五维战场”,雷达作为电磁频谱领域的关键装备,其干扰与抗干扰能力的较量,直接影响着战争的胜负走向。由成都鼎讯科技匠心打造的雷达目标与干扰模拟器,凭借数字射…...

Spring数据访问模块设计
前面我们已经完成了IoC和web模块的设计,聪明的码友立马就知道了,该到数据访问模块了,要不就这俩玩个6啊,查库势在必行,至此,它来了。 一、核心设计理念 1、痛点在哪 应用离不开数据(数据库、No…...
在QWebEngineView上实现鼠标、触摸等事件捕获的解决方案
这个问题我看其他博主也写了,要么要会员、要么写的乱七八糟。这里我整理一下,把问题说清楚并且给出代码,拿去用就行,照着葫芦画瓢。 问题 在继承QWebEngineView后,重写mousePressEvent或event函数无法捕获鼠标按下事…...

Golang——9、反射和文件操作
反射和文件操作 1、反射1.1、reflect.TypeOf()获取任意值的类型对象1.2、reflect.ValueOf()1.3、结构体反射 2、文件操作2.1、os.Open()打开文件2.2、方式一:使用Read()读取文件2.3、方式二:bufio读取文件2.4、方式三:os.ReadFile读取2.5、写…...
uniapp 实现腾讯云IM群文件上传下载功能
UniApp 集成腾讯云IM实现群文件上传下载功能全攻略 一、功能背景与技术选型 在团队协作场景中,群文件共享是核心需求之一。本文将介绍如何基于腾讯云IMCOS,在uniapp中实现: 群内文件上传/下载文件元数据管理下载进度追踪跨平台文件预览 二…...

ZYNQ学习记录FPGA(一)ZYNQ简介
一、知识准备 1.一些术语,缩写和概念: 1)ZYNQ全称:ZYNQ7000 All Pgrammable SoC 2)SoC:system on chips(片上系统),对比集成电路的SoB(system on board) 3)ARM:处理器…...

【免费数据】2005-2019年我国272个地级市的旅游竞争力多指标数据(33个指标)
旅游业是一个城市的重要产业构成。旅游竞争力是一个城市竞争力的重要构成部分。一个城市的旅游竞争力反映了其在旅游市场竞争中的比较优势。 今日我们分享的是2005-2019年我国272个地级市的旅游竞争力多指标数据!该数据集源自2025年4月发表于《地理学报》的论文成果…...

Python环境安装与虚拟环境配置详解
本文档旨在为Python开发者提供一站式的环境安装与虚拟环境配置指南,适用于Windows、macOS和Linux系统。无论你是初学者还是有经验的开发者,都能在此找到适合自己的环境搭建方法和常见问题的解决方案。 快速开始 一分钟快速安装与虚拟环境配置 # macOS/…...