是什么?
- swagger2是一套使用注解生成api接口的方案。
- swagger-ui是将api接口进行可视化展示的工具。
使用步骤
step1:在依赖中加入依赖:
<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>
step2:开启功能
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 默认不开启swagger
*/
@Value("${swagger.enable:false}")
private boolean swaggerEnable;
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerEnable)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxxxxx.xxxx"))
.build();
}
}
swaggerEnable开关用于控制prod环境不暴露api文档
step3:主要注解功能
| 注解 | 作用 | 属性 |
|---|---|---|
| Api | 在Controller,api的分组 | tags:分组的id,description:api分组的描述 |
| ApiOperation | 一个具体的api | value:api的描述 |
| ApiModel | 结构体 | value:名称 |
| ApiModelProperty | 结构体中字段的定义 | value:描述,required:是否必传 |
step4:看
项目启动后在baseUrl/swagger-ui.html#/查看即可
总结
很显然,这种方式和传统使用外部文档的方式有一定的区别。缺点是要写大量的文档到项目里,可能比直接写文档要复杂一些。优点是代码即文档,不会出现接口动了api没动的尴尬。