前言
现在公司中都使用前后端分离的方式进行开发,比如该项目就是一个纯后端框架。为了前后端更好的对接,就需要编写API文档。
然而手写API文档有如下几个痛点:
- 功能修改后要及时更新文档,很容易出现功能文档不匹配
- 文档更新后,需要及时通知使用的人,很容易造成沟通不及时
- 接口参数和返回结果不明确
- 不能在线直接测试,需要借助工具,如Postman
- 接口文档太多,不好进行管理
这时我们今天的主角——Swagger2,顺利登场,说:这一些都不是问题。
那它到底为什么能够这么嚣张,它的效果又是怎么样的,我们下面来实际操作下。
具体实现
添加Maven依赖
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
创建Swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
// apis 指定生成API的扫描条件
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描包
//.apis(RequestHandlerSelectors.basePackage("com.zhuqc.framework.controller"))
// paths 指定生成API的path
.paths(PathSelectors.any())
.build()
// 文档信息
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("从零搭建后端框架")
.description("API接口文档")
.termsOfServiceUrl("https://github.com/zhuqianchang/framework")
.contact(new Contact("zhuqianchang", "", ""))
.version("0.0.1")
.build();
}
}
- @EnableSwagger2 开启Swagger2
- apis 用来指定扫描的条件
- RequestHandlerSelectors.basePackage("com.zhuqc.framework.controller"),扫描指定包
- RequestHandlerSelectors.withClassAnnotation((Api.class),扫描@Api标注的类
- RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class),扫描@ApiOperation标注的方法
- RequestHandlerSelectors.any(),总是true
- RequestHandlerSelectors.none(),总是false
- 默认配置是没有@ApiIgnore标注的类和方法
- paths 用来指定生成API的path
- PathSelectors.any(),总是true
- PathSelectors.none(),总是false
- PathSelectors.regex(),正则表达式匹配
- PathSelectors.ant(),Ant表达式匹配
- apiInfo 用来指定文档信息
Swagger使用
@Api(description = "Hello服务")
@RestController
public class HelloController {
@ApiOperation(value = "打招呼", notes = "打招呼详情描述")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户名", required = true)
})
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name) {
return String.format("Hello %s!", name);
}
}
常见注解
- @Api 修饰整个类,描述整个Controller的作用
- @ApiOperation 修饰方法,描述方法的作用
- @ApiParam 修饰参数,描述参数的作用
- @ApiIgnore 表示忽略当前API
- @ApiImplicitParams 描述多个请求参数
- @ApiImplicitParam 描述一个请求参数
- @ApiModel 如果参数是对象,则在对象所在类上标注,用于描述对象
- @ApiModelProperty 如果参数是对象,则在对象所在类的属性上标注,用于描述对象的属性
启动项目
准备工作已完成,启动项目后访问Swagger地址:http://localhost:8080/swagger-ui.html
测试效果如下:
至此,Swagger2已集成完成。我们要养成在开发或修改完接口的同时,顺手修改下接口描述。这样在与前端对接的时候,只要甩给他一个Swagger地址即可。
常见问题
在实际操作中,可能出现如下问题:
这是由于没有添加注解@EnableSwagger2导致,添加完重启项目即可。