一、关于swagger

1、什么是swagger?

swagger是spring fox的一套产品,可以作为后端开发者测试接口的工具,也可以作为前端取数据的接口文档。

2、为什么使用?

相比于传统的接口文档书写,开发者可以以更高的效率来进行接口测试与开发。而且使得更具可读性。

3、怎样配置?

引入依赖

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.</version>
</dependency>

一篇文章教你快速上手接口管理工具swagger-LMLPHP

配置代码

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration // 注册成ioc组件
@EnableSwagger2 //开启swagger2
public class SwaggerConfig { // 扫描所有带@ApiOperation注解的类
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build();
} //api接口作者相关信息
private ApiInfo apiInfo() {
Contact contact = new Contact("与李", "", "1451633962@qq.com");
ApiInfo apiInfo = new ApiInfoBuilder().license("").title("CSDN").description("接口文档").contact(contact).version("3.0").build();
return apiInfo;
}
}

二、使用教程

@Api :对rest接口类的注解

--value 对资源的标签名

--description 描述

@ApiOperation :对方法的注解

--value 对资源的标签名

--notes 对方法操作的描述

@ApiImplicitParams :对多个参数的描述的集合

@ApiImplicitParam:在@ApiImplicitParams里面

--name 属性字段名

--value 属性字段含义

--required 是否必填(true/false)

--paramType 参数位置("query"为参数放置url,"body"为post方法放在body里...)

--dataType 参数类型("String"、"int"...)

@ApiModel :对实体类的描述

@ApiModelProperty :对实体字段的描述

--name 属性名称

--value 属性描述

--hidden 是否不再swagger页面展示(true/false)

三、踩过的坑

1、swagger-ui页面卡死

一篇文章教你快速上手接口管理工具swagger-LMLPHP一篇文章教你快速上手接口管理工具swagger-LMLPHP

原因:返回的实体或者入参实体中字段重复嵌套,导致swagger页面在展示model时需要大量循环计算,导致cpu占满,浏览器资源耗尽导致页面卡死。

解决方案:

方案1、注意实体中字段的数据的嵌套,隐藏改字段或者修改实体,避免嵌套。

方案2、不用swagger,用其他接口测试工具(0_0)

2、POST请求时,Data Type未显示字段注释

一篇文章教你快速上手接口管理工具swagger-LMLPHP一篇文章教你快速上手接口管理工具swagger-LMLPHP

解决方案:

给请求实体加上@RequestBody注解

一篇文章教你快速上手接口管理工具swagger-LMLPHP一篇文章教你快速上手接口管理工具swagger-LMLPHP

一篇文章教你快速上手接口管理工具swagger-LMLPHP一篇文章教你快速上手接口管理工具swagger-LMLPHP

04-26 04:47