点击上方蓝色“程序猿DD”,选择“设为星标”

回复“资源”获取独家整理的学习资料!

作者 | developlee

来源 | 公众号「锅外的大佬」

1. 概述

公司正好最近在整理项目的文档,且文档对于构建REST API来说是至关重要的。在这篇文章中,我将介绍Spring Doc , 一个基于OpenAPI 3规范简化了Spring Boot 1.x2.x应用程序的API文档的生成和维护的工具。

2. 设置springdoc-openapi

如果想让 springdoc-openapi 为我们的API生成标准的 OpenAPI 3 文档, 只需要添加 [springdoc-openapi-core](https://search.maven.org/search?q=g:org.springdoc AND a:springdoc-openapi-core&core=gav) 依赖到 pom.xml:

<dependency>    <groupId>org.springdoc</groupId>    <artifactId>springdoc-openapi-core</artifactId>    <version>1.1.45</version></dependency>

添加完成后,启动应用程序,即可访问默认路径/v3/api-docs 查看文档,如下所示:

http://localhost:8080/v3/api-docs/

如果想要自定义路径,可在 application.properties 文件中指定 :

springdoc.api-docs.path=/api-docs

这样,文档的访问路径就变成 :

http://localhost:8080/api-docs/

openapi3

OpenAPI 默认定义为JSON 格式。对于 yaml 格式,可以访问下面的路径获取 :

http://localhost:8080/api-docs.yaml

3.整合springdoc-openapi 和Swagger UI

除了自己生成OpenAPI 3规范外,我们还可以将springdoc-openapiSwagger UI集成在一起,以便可以与我们的API规范进行交互并测试端点。

3.1. Maven 依赖

要整合springdoc-openapi 和 Swagger UI , 唯一要做的就是添加springdoc-openapi-ui依赖到项目pom.xml文件中。

<dependency>    <groupId>org.springdoc</groupId>    <artifactId>springdoc-openapi-ui</artifactId>    <version>1.1.45</version></dependency>

访问swagger-ui页面:

http://localhost:8080/swagger-ui.html

当然也可以像上面一样,自定义访问路径:

springdoc.swagger-ui.path=/swagger-ui-custom.html

3.2. 举个栗子

假设有个球(国足令人伤心,所以需要个球啊!!)的controller。

@RestController@RequestMapping("/api/ball")public class BallController {     @Autowired    private BallRepository repository;     @GetMapping("/{id}")    public Ball findById(@PathVariable long id) {        return repository.findById(id)            .orElseThrow(() -> new BallNotFoundException());    }     @GetMapping("/")    public Collection<Book> findBooks() {        return repository.getBooks();    }     @PutMapping("/{id}")    @ResponseStatus(HttpStatus.OK)    public Book updateBook(@PathVariable("id") final String id, @RequestBody final Book book) {        return book;    }}

启动项目,在浏览器中访问地址:

http://localhost:8080/swagger-ui-custom.html

swagger-ui的界面:

swagger-ui

4. springdoc-openapi 与Spring WebFlux集成

我们可以在Spring WebFlux 项目中通过添加依赖:springdoc-openapi-webflux-uispringdoc-openapi and Swagger UI 集成:

<dependency>    <groupId>org.springdoc</groupId>    <artifactId>springdoc-openapi-webflux-ui</artifactId>    <version>1.1.45</version></dependency>

然后,浏览器访问地址

http://localhost:8080/swagger-ui.html

同样的,可以通过添加 springdoc.swagger-ui.path 配置项到 application.properties文件来自定义文档访问路径。

5. 使用springdoc-openapi Maven 插件

springdoc-openapi 库提供了 springdoc-openapi-maven-plugin插件,用来生成JSON或者yaml格式的Open API 描述。

springdoc-openapi-maven-plugin 依赖于 spring-boot-maven 插件. Maven在集成测试阶段运行openapi插件。

那么,如何在pom.xml中配置插件呢?请看下面的代码:

<plugin>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-maven-plugin</artifactId>    <version>2.1.8.RELEASE</version>    <executions>        <execution>            <id>pre-integration-test</id>            <goals>                <goal>start</goal>            </goals>        </execution>        <execution>            <id>post-integration-test</id>            <goals>                <goal>stop</goal>            </goals>        </execution>    </executions></plugin><plugin>    <groupId>org.springdoc</groupId>    <artifactId>springdoc-openapi-maven-plugin</artifactId>    <version>0.2</version>    <executions>        <execution>            <phase>integration-test</phase>            <goals>                <goal>generate</goal>            </goals>        </execution>    </executions></plugin>

当然, 也可以用自定义值来配置插件:

<plugin>    <executions>        .........    </executions>    <configuration>         <apiDocsUrl>http://localhost:8080/v3/api-docs</apiDocsUrl>         <outputFileName>openapi.json</outputFileName>         <outputDir>${project.build.directory}</outputDir>     </configuration></plugin>

仔细看看我们在插件中配置的几个参数:

  • apiDocsUrl – 访问json格式文档的URL, 默认路径:http://localhost:8080/v3/api-docs

  • outputFileName – 存放定义的路径, 默认为:openapi.json

  • outputDir – 文档存放的绝对路径–默认为:${project.build.directory}

6. 使用 JSR-303 Bean Validation 自动生成文档

当我们在模型中使用 JSR-303 bean validation 注解, 诸如 @NotNull@NotBlank@Size@Min@Max等, springdoc-openapi 会为这些bean生成相应的约束。

举个栗子:

public class Ball {     private long id;     @NotBlank    @Size(min = 0, max = 20)    private String title;     @NotBlank    @Size(min = 0, max = 30)    private String author; }

Ball bean生成的文档内容更为丰富:

7. 使用 @ControllerAdvice和@ResponseStatus生成文档

在*@RestControllerAdvice注解的类中,在方法上使用@ResponseStatus会自动生成带有返回状态码的文档。如以下被@ControllerAdvice注解的类中,@ResponseStatus*修饰的两个方法:

@RestControllerAdvicepublic class GlobalControllerExceptionHandler {     @ExceptionHandler(ConversionFailedException.class)    @ResponseStatus(HttpStatus.BAD_REQUEST)    public ResponseEntity<String> handleConnversion(RuntimeException ex) {        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);    }         @ExceptionHandler(BallNotFoundException.class)    @ResponseStatus(HttpStatus.NOT_FOUND)    public ResponseEntity<String> handleBallNotFound(RuntimeException ex) {        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);    }}

现在我们可以在文档中看到返回状态码为400和404。

8. 小结

Spring Boot 2.2.x版本目前可能不支持,因此使用时最好使用2.1.x ,本文所使用Spring Boot版本 2.1.8.RELEASE。

有兴趣的朋友可以自己动手试一下,以上代码可在我的github中找到, over on GitHub.

本文通过OpenWrite的Markdown转换工具发布

关注我,回复“加群”加入各种主题讨论群

  • 使用 LocalDateTime 而不是 Date

  • 深入解读阿里云Redis开发规范:不要只会set&get

  • 在服务器上排除问题的头 5 分钟

  • 多个Java版本如何灵活切换和管理?

  • Spring 体系常用项目一览

  • 阿里规定超过三张表禁止JOIN,为啥?

朕已阅 

Spring Doc 生成OPEN API 3文档相关推荐

  1. 整合swagger2生成Restful Api接口文档

    整合swagger2生成Restful Api接口文档 swagger Restful文档生成工具 2017-9-30 官方地址:https://swagger.io/docs/specificati ...

  2. Swagger 生成 PHP API 接口文档

    Swagger 生成 PHP API 接口文档 标签(空格分隔): php 1.概况 有同学反馈写几十个接口文档需要两天的工作量, 随着多部门之间的协作越来越频繁, 维护成本越来越高, 文档的可维护性 ...

  3. Spring Boot集成Restful Api在线文档接口调试工具 Swagger

    文章目录 一.Swagger简介 Swagger有什么用? 二.环境准备 三.构建Spring Boot工程 四.引入Swagger依赖 五.编写一个Test控制器 六.配置Swagger 七.最终测 ...

  4. 芋道 Spring Boot API 接口文档 Swagger 入门

    点击上方"芋道源码",选择"设为星标" 做积极的人,而不是积极废人! 源码精品专栏 原创 | Java 2020 超神之路,很肝~ 中文详细注释的开源项目 RP ...

  5. Spring Boot 使用 Swagger3 生成 API 接口文档

    前言 在之前的文章中,我们已经讲了如何利用 Spring Boot 来集成 Swagger2,详情可戳:Spring Boot 集成 Swagger2,构建强大的 API 文档.但其实 Swagger ...

  6. Swagger 生成 PHP restful API 接口文档

    需求和背景 需求: 为客户端同事写接口文档的各位后端同学,已经在各种场合回忆了使用自动化文档工具前手写文档的血泪史. 我的故事却又不同,因为首先来说,我在公司是 Android 组负责人,属于上述血泪 ...

  7. Laravel使用swagger PHP生成api接口文档

    Laravel使用swagger PHP生成api接口文档 Swagger集接口文档和测试于一体,就类比将postman和showdoc的结合体 首先要先安装基于laravel5的swagger包 地 ...

  8. springboot(05)整合 Swagger3 生成 API 接口文档

    Spring Boot 集成 Swagger3 Swagger是一种开源的API文档工具,它可以自动生成RESTful API文档,让开发者可以更容易地理解和使用API.使用Swagger可以提高开发 ...

  9. 开发日记-20190328 关键词 利用eolinker一键快速生成API接口文档

    今天感觉效率真的很低= =各个层面的,apk发布到现场发现出现了问题,所以一个下午都在忙着解决现场出现的问题,领导一直打电话询问进度,午觉也没有睡所以今天预计的很多计划都处于停滞状态,像昨天规划的今天 ...

最新文章

  1. drupal与html转换,Drupal 7修改網頁HTML和顯示Title的辦法
  2. Python id() 函数
  3. OpenAI智能体上演捉迷藏攻防大战,自创套路与反套路
  4. shiro教程:session管理
  5. JavaScript 数组拼接打印_巧用控制台,提升JavaScript调试性能
  6. nodejs常用模块-url
  7. 计算机网络课程设计之电子邮件客户端程序设计与实现
  8. 2015年度“最佳技术团队”和“最佳CTO”评选活动火热进行中
  9. linux下设置SMTP服务器并用mail命令发送邮件精解
  10. 2017 Multi-University Training Contest - Team 4:1003. Counting Divisors(积性函数)
  11. mysql 授权远程连接_MySQL远程访问授权
  12. gif一键抠图 在线_在线抠图网站,轻松搞定抠图,效果堪比PS!
  13. 面试题10:青蛙跳台阶
  14. matlab 收敛,MATLAB:svds()没有收敛
  15. 正规蓝牙耳机一般多少钱?音质好又便宜的蓝牙耳机
  16. GRU和LSTM的单元结构
  17. Arcgis 地理坐标系转投影坐标系(WGS84转CGCS2000)
  18. The server time zone value ‘ й ׼ʱ ‘ is unrecognized or represents more than one time zone. You mu
  19. 十三 Keras卷积神经网络 cifar10
  20. FLASH中button组件的selected和toggle属性解析

热门文章

  1. golang 获取两个时间 相差多少 小时
  2. javascript es6 特性简介
  3. linux shell 计算时间差
  4. linux ulimit命令 控制shell执行程序的资源
  5. linux xargs 给命令传递参数 组合多个命令
  6. MFC中CArray类原理及其应用
  7. (二)Amazon Lightsail 部署LAMP应用程序之部署单片LAMP应用程序
  8. VMware host-only模式上网设置
  9. 网络工程制图论文计算机,学习系统与工程制图论文
  10. 问题集锦(26-29)