使用 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”后缀的文件: 这些文件通常包含标准的、核心…...
AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南
点一下关注吧!!!非常感谢!!持续更新!!! 🚀 AI篇持续更新中!(长期更新) 目前2025年06月05日更新到: AI炼丹日志-28 - Aud…...
多模态2025:技术路线“神仙打架”,视频生成冲上云霄
文|魏琳华 编|王一粟 一场大会,聚集了中国多模态大模型的“半壁江山”。 智源大会2025为期两天的论坛中,汇集了学界、创业公司和大厂等三方的热门选手,关于多模态的集中讨论达到了前所未有的热度。其中,…...
条件运算符
C中的三目运算符(也称条件运算符,英文:ternary operator)是一种简洁的条件选择语句,语法如下: 条件表达式 ? 表达式1 : 表达式2• 如果“条件表达式”为true,则整个表达式的结果为“表达式1”…...
postgresql|数据库|只读用户的创建和删除(备忘)
CREATE USER read_only WITH PASSWORD 密码 -- 连接到xxx数据库 \c xxx -- 授予对xxx数据库的只读权限 GRANT CONNECT ON DATABASE xxx TO read_only; GRANT USAGE ON SCHEMA public TO read_only; GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only; GRANT EXECUTE O…...
【算法训练营Day07】字符串part1
文章目录 反转字符串反转字符串II替换数字 反转字符串 题目链接:344. 反转字符串 双指针法,两个指针的元素直接调转即可 class Solution {public void reverseString(char[] s) {int head 0;int end s.length - 1;while(head < end) {char temp …...
SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现
摘要 本论文旨在设计并实现基于 SpringBoot 和 uniapp 的 Champion 俱乐部微信小程序,以满足俱乐部线上活动推广、会员管理、社交互动等需求。通过 SpringBoot 搭建后端服务,提供稳定高效的数据处理与业务逻辑支持;利用 uniapp 实现跨平台前…...
Linux云原生安全:零信任架构与机密计算
Linux云原生安全:零信任架构与机密计算 构建坚不可摧的云原生防御体系 引言:云原生安全的范式革命 随着云原生技术的普及,安全边界正在从传统的网络边界向工作负载内部转移。Gartner预测,到2025年,零信任架构将成为超…...
04-初识css
一、css样式引入 1.1.内部样式 <div style"width: 100px;"></div>1.2.外部样式 1.2.1.外部样式1 <style>.aa {width: 100px;} </style> <div class"aa"></div>1.2.2.外部样式2 <!-- rel内表面引入的是style样…...
涂鸦T5AI手搓语音、emoji、otto机器人从入门到实战
“🤖手搓TuyaAI语音指令 😍秒变表情包大师,让萌系Otto机器人🔥玩出智能新花样!开整!” 🤖 Otto机器人 → 直接点明主体 手搓TuyaAI语音 → 强调 自主编程/自定义 语音控制(TuyaAI…...
NFT模式:数字资产确权与链游经济系统构建
NFT模式:数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新:构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议:基于LayerZero协议实现以太坊、Solana等公链资产互通,通过零知…...
