SpringBoot 如何整合Swagger2 (为方便接口测试)
一:什么是swagger
swagger是一个流行的API开发框架,这个框架以“开放式API声明”(OpenAPI Specification,OAS)为基础,对整个API的开发周期都提供了相应的解决方案,是一个非常庞大的项目(包括设计、编码和测试,几乎支持所有语言)。
OAS本身是一个API规范,它用于描述一整套API接口,包括一个接口是GET还是POST请求啊,有哪些参数哪些header啊,都会被包括在这个文件中。它在设计的时候通常是YAML格式,这种格式书写起来比较方便,而在网络中传输时又会以json形式居多,因为json的通用性比较强。
由于Spring的流行,Marty Pitt编写了一个基于Spring的组件swagger-springmvc,用于将swagger集成到springmvc中来。而springfox则是从这个组件发展而来,同时springfox也是一个新的项目,本文仍然是使用其中的一个组件springfox-swagger2。
二:swagger2相关依赖
<!--SpringBoot 整合Swagger,方便测试后台的restful接口 Swagger UI 查看地址:localhost:8888/swagger-ui.html --> <!-- https://blog.csdn.net/Alexshi5/article/details/89606232--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
三:添加文档内容 在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParam注解来给参数增加说明。
@ApiOperation(value = "全文检索(不带分页)") @ApiImplicitParam(name = "q",value = "全文检索的关键字",required = false, dataType = "String",paramType = "path") @GetMapping("/getUser/{id}") // @RequestMapping("getUser/{id}") public String GetUser(@PathVariable int id){ return userService.getById(id).toString(); }
四:检测接口文档
http://localhost:8888/swagger-ui.html#!/user-controller/GetUserUsingGET