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形式的接口文档

如果要关闭, 启用, 自定义接口地址, 在 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的更多相关文章

  1. spring boot 学习(六)spring boot 各版本中使用 log4j2 记录日志

    spring boot 各版本中使用 log4j2 记录日志 前言 Spring Boot中默认日志工具是 logback,只不过我不太喜欢 logback.为了更好支持 spring boot 框架 ...

  2. Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题【转】

    Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题 http://blog.didispace.com/Spring-Boot-And-Feign- ...

  3. Spring Boot源码中模块详解

    Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...

  4. 阿里P7级教你如何在Spring Boot应用程序中使用Redis

    在Spring Boot应用程序中使用Redis缓存的步骤: 1.要获得Redis连接,我们可以使用Lettuce或Jedis客户端库,Spring Boot 2.0启动程序spring-boot-s ...

  5. Spring Boot 计划任务中的一个“坑”

    计划任务功能在应用程序及其常见,使用Spring Boot的@Scheduled 注解可以很方便的定义一个计划任务.然而在实际开发过程当中还应该注意它的计划任务默认是放在容量为1个线程的线程池中执行, ...

  6. IDEA问题之“微服务启动项目时,不会加载Spring Boot到Services中”

    1.启动项目时,不会加载Spring Boot到Services中 现象解析: 启动项目时 会在debug的位置加载项目 注:这里没有配图,因为问题已解决,未记录图,需往后遇到记录 解决方案: 需要在 ...

  7. 自制Https证书并在Spring Boot和Nginx中使用

    白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环 ...

  8. 自制Https证书并在Spring Boot和Nginx中使用(转)

    白话Https一文中, 介绍了Https存在的目的和工作原理,但多是偏向于原理性的介绍,本文介绍如何一步一步自制一个能够通过浏览器认证的Https证书,并讲解在Spring Boot环境和Nginx环 ...

  9. 学习Spring Boot:(二十七)Spring Boot 2.0 中使用 Actuator

    前言 主要是完成微服务的监控,完成监控治理.可以查看微服务间的数据处理和调用,当它们之间出现了异常,就可以快速定位到出现问题的地方. springboot - version: 2.0 正文 依赖 m ...

  10. Spring Boot 在IDEA中debug时的hot deployment(热部署)

    因为Spring Boot的项目一般会打包成jar发布, 在开发阶段debug时, 不能像传统的web项目那样, 选择exploded resources进行debug, 也没有热更新按钮, 如果每次 ...

随机推荐

  1. 隐私计算之多方安全计算(MPC,Secure Multi-Party Computation)

    作者:京东科技隐私计算产品部 杨博 1.背景 如今,组织在收集.存储敏感的个人信息以及在外部环境(例如云​​)中处理.共享个人信息时, 越来越关注数据安全.这是遵守隐私法规的强需求:例如美国加利福尼亚 ...

  2. vue3中context.emit遇见的坑

    场景描述 今天遇见一个问题 ,子组件向上抛出去的事件. 被执行了两次,原因是 context.emit('click', item.id) 你的事件名是click 将click更改为其他事件名称,就可 ...

  3. 去除elementUI中tab组件中的下划线

    <div class="right-tabbox-newnotice"> <el-tabs v-model="activeName" @tab ...

  4. (数据科学学习手札113)Python+Dash快速web应用开发——表单控件篇(下)

    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 由我开源的先进Dash组件库feffery-antd-co ...

  5. 【译】PEP-3129 类装饰器

    PEP原文 : https://www.python.org/dev/peps/pep-3129 PEP标题: Class Decorators PEP作者: Collin Winter 创建日期: ...

  6. 关于 React 的作业(未完结)

    一.输出 Hello React 信息到网页的程序,非JSX的写法 代码实现如下: <!DOCTYPE html> <html lang="en"> < ...

  7. 多路转接高性能IO服务器|select|poll|epoll|模型详细实现

    前言 那么这里博主先安利一下一些干货满满的专栏啦! Linux专栏https://blog.csdn.net/yu_cblog/category_11786077.html?spm=1001.2014 ...

  8. 【奶奶看了也不会】AI绘画 Mac安装stable-diffusion-webui绘制AI妹子保姆级教程

    1.作品图 2.准备工作 目前网上能搜到的stable-diffusion-webui的安装教程都是Window和Mac M1芯片的,而对于因特尔芯片的文章少之又少,这就导致我们还在用老Intel 芯 ...

  9. git常用命令(企业级)

    一: 常用git命令 # 初始化,将已有的文件初始化为git仓库 git init # 查询文件状态[绿色暂存区,红色表示工作区更改了,没有提交到暂存区] git status git status ...

  10. 完蛋,我被offer包围了|秋招自救指南

    前言 白泽时隔8年终于记起了b站的密码,这篇文章的视频讲解版已经上传,出镜怪不好意思的,后面写技术文章也会同步用视频的方式讲解,期待您的关注. 公众号:白泽talk,交流群:622383022. 大家 ...