在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3
SpringDoc V1 只支持到 Spring Boot 2.x
springdoc-openapi v1.7.0 is the latest Open Source release supporting Spring Boot 2.x and 1.x.
Spring Boot 3.x 要用 SpringDoc 2 / Swagger V3, 并且包名也改成了 springdoc-openapi-starter-webmvc-ui
SpringDoc V2 https://springdoc.org/v2/
配置
增加 Swagger 只需要在 pom.xml 中添加依赖
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version>
</dependency>
Spring Boot 启动时就会自动启用 Swagger, 从以下地址可以访问 接口形式(JSON, YAML)和WEB形式的接口文档
- http://host:port/context-path/v3/api-docs
- YAML格式 http://host:port/context-path/v3/api-docs.yaml
- http://host:port/context-path/swagger-ui/index.html
如果要关闭, 启用, 自定义接口地址, 在 application.yml 中添加配置
springdoc:
api-docs:
path: /v3/api-docs
enabled: false
对应WEB地址的配置为
springdoc:
swagger-ui:
path: /swagger-ui.html
enabled: false
因为WEB界面的显示基于解析JSON接口返回的结果, 如果api-docs关闭, swagger-ui即使enable也无法使用
在开发和测试环境启动服务时, 可以用VM参数分别启用
# in VM arguments
-Dspringdoc.api-docs.enabled=true -Dspringdoc.swagger-ui.enabled=true
使用注解
@Tag
Swagger3 中可以用 @Tag 作为标签, 将接口方法进行分组. 一般定义在 Controller 上, 如果 Controller 没用 @Tag 注解, Swagger3 会用Controller的类名作为默认的Tag, 下面例子用 @Tag 定义了一个“Tutorial”标签, 带有说明"Tutorial management APIs", 将该标签应用于TutorialController后, 在 Swagger3 界面上看到的这个 Controller 下面的方法集合就是 Tutorial.
@Tag(name = "Tutorial", description = "Tutorial management APIs")
@RestController
@RequestMapping("/api")
public class TutorialController {
//...
}
也可以将 @Tag 添加到单独的方法上, 这样在 Swagger3 界面上, 就会将这个方法跟同样是 Tutorial 标签的其它方法集合在一起.
public class AnotherController {
@Tag(name = "Tutorial", description = "Tutorial APIs")
@PostMapping("/tutorials")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
//...
}
}
@Operation
Swagger3中 @Operation注解用于单个API方法. 例如
public class MoreController {
@Operation(
summary = "Retrieve a Tutorial by Id",
description = "Some description",
tags = { "tutorials", "get" })
@GetMapping("/tutorials/{id}")
public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {
//...
}
}
用tags = { "tutorials", "get" }可以将一个方法放到多个Tag分组中
@ApiResponses 和 @ApiResponse
Swagger3 使用 @ApiResponses 注解标识结果类型列表, 用@ApiResponse注解描述各个类型. 例如
public class AnotherController {
@ApiResponses({
@ApiResponse(
responseCode = "200",
content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),
@ApiResponse(
responseCode = "404",
description = "User not found.", content = { @Content(schema = @Schema()) })
})
@GetMapping("/user/{id}")
public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {
return null;
}
}
@Parameter
@Parameter注解用于描述方法参数, 例如:
@GetMapping("/tutorials")
public ResponseEntity<Map<String, Object>> getAllTutorials(
@Parameter(description = "Search Tutorials by title") @RequestParam(required = false) String title,
@Parameter(description = "Page number, starting from 0", required = true) @RequestParam(defaultValue = "0") int page,
@Parameter(description = "Number of items per page", required = true) @RequestParam(defaultValue = "3") int size) {
//...
}
@Schema annotation
Swagger3 用 @Schema 注解对象和字段, 以及接口中的参数类型, 例如
@Schema(description = "Tutorial Model Information")
public class Tutorial {
@Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "Tutorial Id", example = "123")
private long id;
@Schema(description = "Tutorial's title", example = "Swagger Tutorial")
private String title;
// getters and setters
}
accessMode = Schema.AccessMode.READ_ONLY用于在接口定义中标识字段只读
实例
定义接口
@Tag(
name = "CRUD REST APIs for User Resource",
description = "CRUD REST APIs - Create User, Update User, Get User, Get All Users, Delete User"
)
@Slf4j
@RestController
public class IndexController {
@Operation(summary = "Get a user by its id")
@GetMapping(value = "/user_get")
public String doGetUser(
@Parameter(name = "id", description = "id of user to be searched")
@RequestParam(name = "id", required = true)
String id) {
return "doGetUser: " + id;
}
@Operation(summary = "Add a user")
@PostMapping(value = "/user_add")
public String doAddUser(
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true)
@RequestBody UserBO user) {
return "doAddUser: " + user.getName();
}
@ApiResponses({
@ApiResponse(
responseCode = "200",
content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),
@ApiResponse(
responseCode = "404",
description = "User not found.", content = { @Content(schema = @Schema()) })
})
@GetMapping("/user/{id}")
public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {
return null;
}
}
对于这行代码@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true),
因为 Swagger3 的 RequestBody 类和 Spring MVC 的 RequestBody 重名了, 所以在注释中不得不用完整路径, 比较影响代码格式. 在GitHub上有对这个问题的讨论(链接 https://github.com/swagger-api/swagger-core/issues/3628), 暂时无解.
定义对象
@Schema(description = "UserBO Model Information")
@Data
public class UserBO {
@Schema(description = "User ID")
private String id;
@Schema(description = "User Name")
private String name;
}
参考
在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3的更多相关文章
- spring boot 学习(六)spring boot 各版本中使用 log4j2 记录日志
spring boot 各版本中使用 log4j2 记录日志 前言 Spring Boot中默认日志工具是 logback,只不过我不太喜欢 logback.为了更好支持 spring boot 框架 ...
- Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题【转】
Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题 http://blog.didispace.com/Spring-Boot-And-Feign- ...
- Spring Boot源码中模块详解
Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...
- 阿里P7级教你如何在Spring Boot应用程序中使用Redis
在Spring Boot应用程序中使用Redis缓存的步骤: 1.要获得Redis连接,我们可以使用Lettuce或Jedis客户端库,Spring Boot 2.0启动程序spring-boot-s ...
- Spring Boot 计划任务中的一个“坑”
计划任务功能在应用程序及其常见,使用Spring Boot的@Scheduled 注解可以很方便的定义一个计划任务.然而在实际开发过程当中还应该注意它的计划任务默认是放在容量为1个线程的线程池中执行, ...
- IDEA问题之“微服务启动项目时,不会加载Spring Boot到Services中”
1.启动项目时,不会加载Spring Boot到Services中 现象解析: 启动项目时 会在debug的位置加载项目 注:这里没有配图,因为问题已解决,未记录图,需往后遇到记录 解决方案: 需要在 ...
- 自制Https证书并在Spring Boot和Nginx中使用
白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环 ...
- 自制Https证书并在Spring Boot和Nginx中使用(转)
白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环 ...
- 学习Spring Boot:(二十七)Spring Boot 2.0 中使用 Actuator
前言 主要是完成微服务的监控,完成监控治理.可以查看微服务间的数据处理和调用,当它们之间出现了异常,就可以快速定位到出现问题的地方. springboot - version: 2.0 正文 依赖 m ...
- Spring Boot 在IDEA中debug时的hot deployment(热部署)
因为Spring Boot的项目一般会打包成jar发布, 在开发阶段debug时, 不能像传统的web项目那样, 选择exploded resources进行debug, 也没有热更新按钮, 如果每次 ...
随机推荐
- Spring缓存是如何实现的?如何扩展使其支持过期删除功能?
前言:在我们的应用中,有一些数据是通过rpc获取的远端数据,该数据不会经常变化,允许客户端在本地缓存一定时间. 该场景逻辑简单,缓存数据较小,不需要持久化,所以不希望引入其他第三方缓存工具加重应用负担 ...
- node中的fs模块和http模块的学习
读取文件 fs 模块 第1个参数就是要读取的文件路径 第2个参数是一个回调函数(error,data)=>{} error 如果读取失败,error 就是错误对象 如果读取成功,error 就是 ...
- React中生命周期的讲解
什么是生命周期? 从出生到成长,最后到死亡,这个过程的时间可以理解为生命周期. React中的组件也是这么一个过程. React的生命周期分为三个阶段:挂载期(也叫实例化期).更新期(也叫存在期).卸 ...
- 让你轻松看懂defer和async
defer和async产生的原因 HTML 网页中,浏览器通过<script>标签加载 JavaScript 脚本. <!-- 页面内嵌的脚本 --> <script t ...
- ABP vNext系列文章04---DynamicClient动态代理
一.动态代理在ABP系统中的应用 1.它主要在做什么事件 之前开发系统想要在后台调用别的服务都是用HttpClient发起请求,在abp vnext中不需要我们这样做了, 你只要知道服务调用的接口方法 ...
- 微信小程序网页嵌入开发
无脑开发 下载微信开发者工具 新建一个项目找到index开头的进去全选删除粘贴下面代码 <!-- html --> <!-- 指向嵌入外部链接的地址 --> <web-v ...
- TienChin 代码格式化-项目结构大改造
代码格式化 博主下载项目之后发现,整体的代码格式化风格,与 C 那种语言很相似,说明这个作者之前就是从事这块的导致风格有点类似,我们来格式化一下,当然这不是必要的,我是没习惯这种写法所以这里我写一下我 ...
- python实现GUI自动化(控制鼠标)|屏幕快照&图像识别基础
1.GUI自动化 ●GUI自动化就是写程序直接控制键盘和鼠标.这些程序可以控制其他应用,向它们发送虚拟的击键和鼠标点击,就像你自己坐在计算机前与应用交互-样.这种技术被称为"图形用户界面自动 ...
- .net 工具箱不可用/怎样初始化vs环境 解决方案
在开始菜单里面执行的.开始菜单->Microsoft Visual Studio 2005->Visual Studio Tools->Visual Studio 2005 命令提示 ...
- TActionManager Delphi 超级方便的快捷键 草草
delphi 中用快捷键 草 实在是 太简单了 . 自己摸索出来的 方法 --------------------------------------------------------------- ...