swagger简介
swagger主要是来生成程序接口的文档、进行方法测试的一个框架。
总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。
swagger两个依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置config类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo());
}
private ApiInfo getApiInfo(){
return new ApiInfo(
"呵呵",
"Api Documentation",
"1.1",
"urn:tos",
getContact(),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
private Contact getContact(){
return new Contact("", "", "");
}
}
过滤接口
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
//可选择按包、按类注解、方法注解、全选、全不选进行过滤
.apis(RequestHandlerSelectors.basePackage("com"))
//按路径进行过滤
.paths(PathSelectors.any())
.build();
}
配置完毕后通过swigger-ui.html进入
分组
通过设置多个Docket的bean进行分组,主要使用groupName对各组进行区分
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("a")
.apiInfo(getApiInfo())
.select()
//可选择按包、按类注解、方法注解、全选、全不选进行过滤
.apis(RequestHandlerSelectors.basePackage("com"))
//按路径进行过滤
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("b");
}
文档注释
- @ApiModel:加在bean上
- @ApiModelProperty:加在bean的属性上
- @ApiOperation:加在方法上
- @ApiParam:加在形参上
方法测试
进入swagger-ui.html后,在每个方法下有一个try it out
的按钮,点击它后输入方法对应的参数后点击execute
即可执行并查看一些请求信息和结果