当前位置: 首页 > news >正文

使用 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.ymlapplication.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 文档的库&#xff0c;它支持与 Spring Boot 无缝集成。通过这个库&#xff0c;你可以轻松地生成和展示 RESTful API 的文档&#xff0c;并且可以使用 Swagger UI 或 ReDoc 进行…...

ssm基于ssm框架的滁艺咖啡在线销售系统+vue

系统包含&#xff1a;源码论文 所用技术&#xff1a;SpringBootVueSSMMybatisMysql 免费提供给大家参考或者学习&#xff0c;获取源码请私聊我 需要定制请私聊 目 录 第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&#xff08;不挂起&#xff09;&#xff0c;用于在系统后台不挂断地运行命令&#xff0c;退出终端不会影响程序的运行。 nohup 命令&#xff0c;在默认情况下&#xff08;非重定向时&#x…...

CSS、Less、Scss

CSS、Less和SCSS都是用于描述网页外观的样式表语言&#xff0c;但它们各自具有不同的特点和功能。以下是对这三者的详细阐述及区别对比&#xff1a; 详细阐述 CSS&#xff08;Cascading Style Sheets&#xff09; 定义&#xff1a;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)

&#x1f449;文末查看项目功能视频演示获取源码sql脚本视频导入教程视频 1 、功能描述 基于SSM的心理咨询管理管理系统拥有三个角色&#xff1a;学生用户、咨询师、管理员 管理员&#xff1a;学生管理、咨询师管理、文档信息管理、预约信息管理、测试题目管理、测试信息管理…...

南开大学《2023年+2022年810自动控制原理真题》 (完整版)

本文内容&#xff0c;全部选自自动化考研联盟的&#xff1a;《南开大学810自控考研资料》的真题篇。后续会持续更新更多学校&#xff0c;更多年份的真题&#xff0c;记得关注哦~ 目录 2023年真题 2022年真题 Part1&#xff1a;2023年2022年完整版真题 2023年真题 2022年真题…...

【算法】Kruskal最小生成树算法

目录 一、最小生成树 二、Kruskal算法求最小生成树 三、代码 一、最小生成树 什么是最小生成树&#xff1f; 对于一个n个节点的带权图&#xff0c;从中选出n-1条边&#xff08;保持每个节点的联通&#xff09;构成一棵树&#xff08;不能带环&#xff09;&#xff0c;使得…...

Pocket通常指的是一种特定的凹形或凹槽

在几何和计算机辅助设计&#xff08;CAD&#xff09;中&#xff0c;“Pocket”通常指的是一种特定的凹形或凹槽&#xff0c;用于表示在物体表面上挖出的区域。其主要特点包括&#xff1a; 凹形区域&#xff1a;Pocket 是一个在三维模型中内凹的区域&#xff0c;通常从物体的表面…...

Cesium基础-(Entity)-(Billboard)

里边包含Vue、React框架代码 2、Billboard 广告牌 Cesium中的Billboard是一种用于在3D场景中添加图像标签的简单方式。Billboard提供了一种方法来显示定向的2D图像,这些图像通常用于表示简单的标记、符号或图标。以下是对Billboard的详细解读: 1. Billboard的定义和特性 B…...

从0到1,解读安卓ASO优化!

大家好&#xff0c;我是互金行业的一名ASO运营专员&#xff0c;目前是负责我们两个APP的ASO方面的维护&#xff0c;今天分享的内容主要是关于安卓ASO优化方案。 大致内容分为三块&#xff1a; 首先我要讲一下ASO是什么&#xff1b;接下来就是安卓的渠道的选择&#xff0c;安卓…...

go语言中流程控制语句

Go语言中的流程控制语句包括条件判断、循环和分支控制。以下是详细介绍&#xff1a; 1. 条件判断语句 if 语句 Go语言的 if 语句与其他语言类似&#xff0c;支持基本的条件判断。 if 条件 {// 执行代码 }if-else 语句&#xff1a; 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;">这是用了内联样式&#xff0c;蓝色</p2><br> 3.外部样式表 在css文件夹里面构建一个css文件…...

Linux之nfs服务器和dns服务器

NFS服务器 NFS&#xff08;Network File System&#xff0c;网络文件系统)&#xff0c;NFS服务器可以让PC将网络中的NFS服务器共享的目录挂载到本地端的文件系统中&#xff0c;而在本地端的系统 中看来&#xff0c;那个远程主机的目录就好像是自己的一个磁盘分区一样。 注&am…...

大模型系列——AlphaZero/强化学习/MCTS

AlphaGo Zero无需任何人类历史棋谱&#xff0c;仅使用深度强化学习&#xff0c;从零开始训练三天的成就已远远超过了人类数千年积累的围棋知识。 1、围棋知识 &#xff08;1&#xff09;如何简单理解围棋知识 &#xff08;2&#xff09;数子法分胜负&#xff1a;https://zhu…...

原生js实现拖拽上传(拖拽时高亮上传区域)

文章目录 drop相关事件说明-MDN演示代码&#xff08;.html) drop相关事件说明-MDN 演示 代码&#xff08;.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 #提供几何形状的操作和分析&#xff0c;如交集、并集、差集等 pip install -i …...

STM32的hal库中,后缀带ex和不带的有什么区别

在STM32的HAL&#xff08;硬件抽象层&#xff09;库中&#xff0c;后缀带“ex”和不带“ex”的文件及其包含的内容存在显著的区别。这些区别主要体现在功能扩展性、使用场景以及API的层次上。 一、功能扩展性 不带“ex”后缀的文件&#xff1a; 这些文件通常包含标准的、核心…...

基于算法竞赛的c++编程(28)结构体的进阶应用

结构体的嵌套与复杂数据组织 在C中&#xff0c;结构体可以嵌套使用&#xff0c;形成更复杂的数据结构。例如&#xff0c;可以通过嵌套结构体描述多层级数据关系&#xff1a; struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

边缘计算医疗风险自查APP开发方案

核心目标:在便携设备(智能手表/家用检测仪)部署轻量化疾病预测模型,实现低延迟、隐私安全的实时健康风险评估。 一、技术架构设计 #mermaid-svg-iuNaeeLK2YoFKfao {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg…...

23-Oracle 23 ai 区块链表(Blockchain Table)

小伙伴有没有在金融强合规的领域中遇见&#xff0c;必须要保持数据不可变&#xff0c;管理员都无法修改和留痕的要求。比如医疗的电子病历中&#xff0c;影像检查检验结果不可篡改行的&#xff0c;药品追溯过程中数据只可插入无法删除的特性需求&#xff1b;登录日志、修改日志…...

为什么需要建设工程项目管理?工程项目管理有哪些亮点功能?

在建筑行业&#xff0c;项目管理的重要性不言而喻。随着工程规模的扩大、技术复杂度的提升&#xff0c;传统的管理模式已经难以满足现代工程的需求。过去&#xff0c;许多企业依赖手工记录、口头沟通和分散的信息管理&#xff0c;导致效率低下、成本失控、风险频发。例如&#…...

《用户共鸣指数(E)驱动品牌大模型种草:如何抢占大模型搜索结果情感高地》

在注意力分散、内容高度同质化的时代&#xff0c;情感连接已成为品牌破圈的关键通道。我们在服务大量品牌客户的过程中发现&#xff0c;消费者对内容的“有感”程度&#xff0c;正日益成为影响品牌传播效率与转化率的核心变量。在生成式AI驱动的内容生成与推荐环境中&#xff0…...

如何在看板中有效管理突发紧急任务

在看板中有效管理突发紧急任务需要&#xff1a;设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP&#xff08;Work-in-Progress&#xff09;弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中&#xff0c;设立专门的紧急任务通道尤为重要&#xff0c;这能…...

镜像里切换为普通用户

如果你登录远程虚拟机默认就是 root 用户&#xff0c;但你不希望用 root 权限运行 ns-3&#xff08;这是对的&#xff0c;ns3 工具会拒绝 root&#xff09;&#xff0c;你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案&#xff1a;创建非 roo…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

QT: `long long` 类型转换为 `QString` 2025.6.5

在 Qt 中&#xff0c;将 long long 类型转换为 QString 可以通过以下两种常用方法实现&#xff1a; 方法 1&#xff1a;使用 QString::number() 直接调用 QString 的静态方法 number()&#xff0c;将数值转换为字符串&#xff1a; long long value 1234567890123456789LL; …...