在 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

相关文章

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Pydantic中Optional 和Union类型的使用

《Pydantic中Optional和Union类型的使用》本文主要介绍了Pydantic中Optional和Union类型的使用,这两者在处理可选字段和多类型字段时尤为重要,文中通过示例代码介绍的... 目录简介Optional 类型Union 类型Optional 和 Union 的组合总结简介Pyd

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti