在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3

2024-03-01 21:20

本文主要是介绍在 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-docsenabled: false

对应WEB地址的配置为

springdoc:swagger-ui:path: /swagger-ui.htmlenabled: 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;
}

参考

  • https://www.baeldung.com/spring-rest-openapi-documentation

这篇关于在 Spring Boot 3.x 中使用 SpringDoc 2 / Swagger V3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/763845

相关文章

springboot控制bean的创建顺序

《springboot控制bean的创建顺序》本文主要介绍了spring-boot控制bean的创建顺序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1、order注解(不一定有效)2、dependsOn注解(有效)3、提前将bean注册为Bea

Java中的ConcurrentBitSet使用小结

《Java中的ConcurrentBitSet使用小结》本文主要介绍了Java中的ConcurrentBitSet使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、核心澄清:Java标准库无内置ConcurrentBitSet二、推荐方案:Eclipse

java中的Supplier接口解析

《java中的Supplier接口解析》Java8引入的Supplier接口是一个无参数函数式接口,通过get()方法延迟计算结果,它适用于按需生成场景,下面就来介绍一下如何使用,感兴趣的可以了解一下... 目录1. 接口定义与核心方法2. 典型使用场景场景1:延迟初始化(Lazy Initializati

Go语言结构体标签(Tag)的使用小结

《Go语言结构体标签(Tag)的使用小结》结构体标签Tag是Go语言中附加在结构体字段后的元数据字符串,用于提供额外的属性信息,这些信息可以通过反射在运行时读取和解析,下面就来详细的介绍一下Tag的使... 目录什么是结构体标签?基本语法常见的标签用途1.jsON 序列化/反序列化(最常用)2.数据库操作(

Java中ScopeValue的使用小结

《Java中ScopeValue的使用小结》Java21引入的ScopedValue是一种作用域内共享不可变数据的预览API,本文就来详细介绍一下Java中ScopeValue的使用小结,感兴趣的可以... 目录一、Java ScopedValue(作用域值)详解1. 定义与背景2. 核心特性3. 使用方法

spring中Interceptor的使用小结

《spring中Interceptor的使用小结》SpringInterceptor是SpringMVC提供的一种机制,用于在请求处理的不同阶段插入自定义逻辑,通过实现HandlerIntercept... 目录一、Interceptor 的核心概念二、Interceptor 的创建与配置三、拦截器的执行顺

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Spring Boot 处理带文件表单的方式汇总

《SpringBoot处理带文件表单的方式汇总》本文详细介绍了六种处理文件上传的方式,包括@RequestParam、@RequestPart、@ModelAttribute、@ModelAttr... 目录方式 1:@RequestParam接收文件后端代码前端代码特点方式 2:@RequestPart接