API文档工具swagger
1.Swagger2介绍
Swagger 是一款RESTFUL接口的、基于YAML、JSON语言的文档在线自动生成、代码自动生成的工具。前后端分离开发模式中,api文档是最好的沟通方式。
及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
可测性 (直接在接口文档上进行测试,以方便理解业务)
官方网站:https://swagger.io/
2.配置Swagger2
1.pom文件中添加依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.创建Swagger的配置文件 SwaggerConfig.java
2.1.基本配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
2.2.启动服务查看接口
端口号是自己测试的微服务端口号,swagger-ui.html是默认主页面
http://localhost:6003/swagger-ui.html
swaggerUI显示
3.分组配置及参数说明
3.1.Docket类
swagger配置类主要依赖于Docket类的实现,在Docket类中有关于分组设置的方法
3.2.配置基本的分组信息
具体详情配置如下图,
①分组信息groupName,swaggerUI显示
②ApiInfo类,填写swagger测试文档描述信息
导入的Contact包为springfox.documentation,service;不要导swagger的
Contact类有具体的联系人描述信息
swaggerUI显示
③ApiSelectorBuilder类,选择过滤哪些请求路径
ApiSelectorBuilder中的方法
4.定义接口说明和参数说明
@Api:定义在类上
@ApiOperation:定义在方法上
@ApiParam:定义在参数上
swaggerUI显示
5.定义entity实体类
5.1.注解,entity的实体类中可以添加一些自定义设置
@ApiModel:定义在entity实体类上
@ApiModelProperty:定义在实体类的属性上
swaggerUI显示
5.2.解决时间格式显示错误
①在@ApiModelProperty中添加example格式样例
②统一返回的json时间格式
默认情况下json时间格式带有时区,并且是世界标准时间,我们在东八区,时间差了八个小时
在application.yml中设置
spring:
jackson: #返回json的全局时间格式
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
swaggerUI显示