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/

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

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

3.整合springdoc-openapi 和Swagger UI

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

3.1. Maven 依赖

要整合springdoc-openapiSwagger 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的界面:

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修饰的两个方法:

@RestControllerAdvice
public 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.


关注公众号: 回复666 领取翻译文章福利:

最新文章

  1. [ZigBee] 16、Zigbee协议栈应用(二)——基于OSAL的无线控制LED闪烁分析(下)
  2. 浅谈JSON
  3. awk 匹配不是 pattern 的内容
  4. div+css树形菜单
  5. Androidclient和server第一种方法端数据交换
  6. 【2017-02-23】switch...case...和for循环
  7. Python之Threading模块
  8. github感悟
  9. Vector与ArrayList区别
  10. centos7搭建elasticsearch
  11. mysql事务四大特性
  12. 20155306 白皎 《网络攻防》 EXP8 Web基础
  13. Java面试题系列(二)Java内存模型
  14. 视图不能由多个 ListView 共享 (View can&#39;t be shared by more than one ListView) 的一个解决方法
  15. centos7安装完成后的一些配置
  16. eureka快速剔除失效服务
  17. 用仿ActionScript的语法来编写html5——第四篇,继承与简单的rpg
  18. mysqldump备份以tmp_开头的表
  19. SQL性能分析
  20. __get(),__set(),__isset(),__unset()

热门文章

  1. halcon学习方法小结及以后的学习计划
  2. Newtonsoft—Json.NET常用方法简述
  3. 美团 iOS 端开源框架 Graver 在动态化上的探索与实践
  4. [NOI2001]食物链(并查集拓展域)&amp;&amp; [HAOI2006]旅行(Kruskal)
  5. js中用面向对象的思想——淡入淡出轮播图
  6. Sping MVC不使用任何注解处理(jQuery)Ajax请求(基于XML配置)
  7. leetcode系列---atoiFunction C#code
  8. python argparse:命令行参数解析详解
  9. Windows 10 + kali Linux 双系统安装教程(详细版)
  10. sql中实现先排序后分组