Loading
Loading...

SpringBoot 使用 Springfox Swagger 3.0 调试接口

系统环境:

  • SpringBoot版本: 2.4.4
  • Springfox 版本: 3.0.0
  • JAVA JDK 版本: 1.8 (最低要求)

参考地址:

示例地址:

一、背景

由于 Spring Boot 能够快速开发、便捷部署等特性,相信有很大一部分 Spring Boot 的用户会用来构建 RESTful API。而我们构建 RESTful API 的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者 Web 前端。

这样一来,我们的 RESTful API 就有可能要面对多个开发人员或多个开发团队:IOS 开发、Android 开发或是 Web 开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份 RESTful API 文档来记录所有接口细节,然而这样的做法有以下几个问题:

  • 由于接口众多,并且细节复杂(需要考虑不同的 HTTP 请求类型、HTTP 头部信息、HTTP 请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。
  • 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

为了解决上面这样的问题,本文将介绍 RESTful API 的重磅好伙伴 Springfox,它可以轻松的整合到 SpringBoot 中,并与 Spring MVC 程序配合组织出强大 RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外 Springfox Swagger 也提供了强大的页面测试功能来调试每个 RESTful API。

二、Swagger简介

Swagger 既是一款接口的文档在线自动生成软件,也是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

三、创建示例项目

Maven 引入 Springfox 依赖

新建 Maven 项目,往其 pom.xml 中引入 Springboot 及 Springfox Swagger 相关依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>club.mydlq</groupId>
<artifactId>springboot-swagger-v3-example</artifactId>
<version>1.0.0</version>
<name>springboot-swagger-v3-example</name>
<description>springboot swagger v3 api example service</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

注意: 由于 SpringBoot 2.6.x 后修改了路由匹配策略,所以需要在启动类或者配置类上加上 @EnableWebMvc,否则启动会报错!!!。

创建 Swagger 配置类

创建 Springfox Swagger 配置类,在该类中可以配置 Swagger 文档的基本信息,下面示例的配置类中本人已经对大部分常用参数标注了详细的说明。

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Value("${springfox.documentation.swagger-ui.enabled}")
private boolean enabled;
@Bean
public Docket createRestApi() {
return new Docket(
// 设置使用 OpenApi 3.0 规范
DocumentationType.OAS_30)
// 是否开启 Swagger
.enable(enabled)
// 配置项目基本信息
.apiInfo(apiInfo())
// 设置项目组名
//.groupName("xxx组")
// 选择那些路径和api会生成document
.select()
// 对所有api进行监控
.apis(RequestHandlerSelectors.any())
// 如果需要指定对某个包的接口进行监控,则可以配置如下
//.apis(RequestHandlerSelectors.basePackage("mydlq.swagger.example.controller"))
// 对所有路径进行监控
.paths(PathSelectors.any())
// 忽略以"/error"开头的路径,可以防止显示如404错误接口
.paths(PathSelectors.regex("/error.*").negate())
// 忽略以"/actuator"开头的路径
.paths(PathSelectors.regex("/actuator.*").negate())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 文档标题
.title("用户服务接口")
// 文档描述
.description("用户相关操作接口")
// 文档版本
.version("0.0.1")
// 设置许可声明信息
.license("Apache LICENSE 2.0")
// 设置许可证URL地址
.licenseUrl("https://github/my-dlq")
// 设置管理该API人员的联系信息
.contact(new Contact("超级小豆丁", "http://www.mydlq.club", "mynamedlq@163.com"))
.build();
}
}

配置文件中添加参数

配置文件 application.yml 中添加 Springfox 的配置参数,现在 springfox-boot-starter 依赖包默认提供了参数 springfox.documentation.swagger-ui.enabled 来控制是否开启 Swagger 文档 UI,并且上面在 Swagger 配置文件中也引用这个参数作为 Swagger API 的开关,我们就能通过这一个参数来管理是否开启 Swagger 了,配置文件内容如下:

spring:
application:
name: springboot-swagger-v3-example
springfox:
documentation:
swagger-ui:
enabled: true

创建测试的 User 实体类

为了方便测试,这里创建一个 User 实体类,并且在类中使用了 Springfox Swagger 的 @ApiModel@ApiModelProperty 两个注解,这些注解都是用于对实体类某个属性描述,方便后续在浏览 Swagger 文档中能知道具体参数的作用。

import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
@ApiModel("用户实体类")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
// @ApiModelProperty:用于描述字段信息
@ApiModelProperty(value = "姓名", required = true)
private String name;
@ApiModelProperty(value = "性别", required = true)
private String sex;
@ApiModelProperty(value = "岁数", required = true)
private Integer age;
@ApiModelProperty(value = "生日")
private Date birthday;
}

上面配置类中使用了 Lombok 依赖的 @Data@NoArgsConstructor@AllArgsConstructor 三个注解,用于生成 get、set 以及无参和多参构造方法,能很方便的简化创建实体类的代码量。

创建示例 Controller 接口

创建一个示例的用户 Controller 类,且使用 Springfox Swagger 注解,对接口的作用进行详细描述。

import io.swagger.annotations.*;
import mydlq.swagger.example.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
@Api(tags = "用户接口")
@RestController
@RequestMapping("/users")
public class UserController {
@ApiOperation(value = "查询用户", notes = "查询用户信息。")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "查询的用户姓名", required = true),
@ApiImplicitParam(name = "age", value = "查询的用户岁数", required = false)
})
@GetMapping(value = "/{name}")
public ResponseEntity<User> findUser(@PathVariable(value = "name", required = true) String name,
@RequestParam(value = "age", required = false) Integer age) {
// 创建模拟数据,然后返回数据
return ResponseEntity.ok(new User(name, "男", age, LocalDateTime.now()));
}
@PostMapping(value = "/")
@ApiOperation(value = "创建用户", notes = "创建新的用户信息。")
public ResponseEntity<String> addUser(@RequestBody User user) {
return ResponseEntity.ok(user.getName() + " created");
}
@PutMapping(value = "/")
@ApiOperation(value = "更新用户", notes = "更新用户信息。")
public ResponseEntity<User> modifyUser(@RequestBody User user) {
return ResponseEntity.ok(user);
}
@DeleteMapping(value = "/{name}")
@ApiOperation(value = "删除用户", notes = "删除用户信息。")
public ResponseEntity<String> deleteUser(@PathVariable(value = "name") String name) {
return ResponseEntity.ok(name + " deleted");
}
}

上面类中使用了几个 Swagger 常用注解,分别为:

  • @Api: 对整个 Controller 接口信息的描述。
  • @ApiOperation: 对某个接口信息进行描述。
  • @ApiImplicitParam: 对请求参数进行描述。
  • @ApiImplicitParams: 用于包含多个 @ApiImplicitParam 注解,对请求中的多个参数进行描述。

以上注解为常用注解,更多可用的注解可以参考 Springfox 文档

创建 SpringBoot 启动类

创建启动类,用于启动 SpringBoot 应用。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

四、访问示例项目

访问 Springfox Swagger API

这里要说的一点就是 Springfox Swagger 项目原理就是生成一个符合指定规范的 API 接口,能够从该接口获取内容信息,然后 Swagger-UI 前端项目会根据该 API 获取的 JSON 信息生成前端文档页面。

本地启动项目,然后输入地址 http://localhost:8080/v3/api-docs,可以看见 Swagger API 接口返回的 JSON 信息,该 JSON 内容符合 OpenAPI 3.0 规范。

{
"openapi": "3.0.3",
"info": {
"title": "用户服务接口",
"description": "用户相关操作接口",
"contact": {
"name": "超级小豆丁",
"url": "http://www.mydlq.club",
"email": "mynamedlq@163.com"
},
"license": {
"name": "Apache LICENSE 2.0",
"url": "https://github/my-dlq"
},
"version": "0.0.1"
},
"servers": [
{
"url": "http://localhost:8080",
"description": "Inferred Url"
}
],
"tags": [
{
"name": "示例接口",
"description": "User Controller"
}
],
"paths": {
"/users/": {
"put": {
"tags": [
"示例接口"
],
"summary": "更新用户",
"description": "更新用户信息。",
"operationId": "modifyUserUsingPUT",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/用户实体类"
}
}
}
}
...(太长,略)

访问 Swagger UI 界面

在 Springfox 项目中,我们可也通过默认的 UI 地址 /swagger-ui/index.html 访问 Swagger 文档。这里本人是本地启动,所以输入地址 http://localhost:8080/swagger-ui/index.html 就能浏览 Swagger 文档页面。

Swagger 文档页面

Swagger 查询用户接口文档

Swagger 用户实体类信息

上面的接口文档界面很清晰,我们可以很方便的使用该文档对接口进行调试。

---END---
如果本文对你有帮助,可以关注我的公众号 "小豆丁技术栈" 了解最新动态,顺便也请帮忙 Github 点颗星哦,感谢~

本文作者:超级小豆丁 @ 小豆丁技术栈

本文链接:http://www.mydlq.club/article/108/

本文标题:SpringBoot 使用 Springfox Swagger 3.0 调试接口

本文版权:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!