Swagger框架——前后端API调试工具
一、简介&常用注解
1.1 简介
Swagger2主要在于前端开发人员与后端开发人员对WebAPI接口的沟通,该框架可以动态生成Api接口在线文档,降低沟通成本,促进项目高效开发。
1.2 常用注解
@Api
:用于controller类上;用于对请求的接口进行描述;@ApiOperation
:用在接口的方法上;用于对请求的接口中的方法进行说明;@ApiParam
:用在方法的参数前面;用于给参数添加说明;@ApiResponse
:用在方法上,对返回的状态码进行说明;(多个状态码说明时可以将该注解放在 @ApiResponses 注解中)- 。。。感兴趣的自己去查阅剩下的注解的含义
可参考:猎人在吃肉
swagger2的全部注解;
二、Swagger使用
2.1 添加依赖
<!--swagger2的依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!--swagger ui的依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.2 配置类(两种)
2.2.1 配置类(匹配对应的包)
@Configuration
//开启swagger2
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) //指定Api类型为Swagger2
.apiInfo(apiInfo()) //指定文档汇总信息
.select()
.apis(RequestHandlerSelectors
.basePackage("com.ccbx.backend.controller")) //指定controller包路径
.paths(PathSelectors.any()) //指定展示所有controller
.build();
}
private ApiInfo apiInfo() {
//返回一个apiinfo
return new ApiInfoBuilder()
.title("xxxx后台管理系统API文档") //文档页标题
.contact( // 联系人信息
new Contact("Jim", "http://www.baidu.com", "111@qq.com")
)
.description("api文档描述") // 描述信息
.version("1.0.1") // 文档版本号
.termsOfServiceUrl("https://www.baidu.com") //服务地址
.build();
}
}
浏览器访问
2.2.2 配置类(匹配请求路径)
/**
* @Description
* @Author cb
* @Date 2021-12-24 20:36
**/
@EnableSwagger2
@SpringBootConfiguration
public class Swagger2Config {
@Bean
public Docket adminApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
//如果存在多个 Docket 实例,则每个实例都必须具有此方法提供的唯一 groupName
.groupName("adminApi")
.apiInfo(adminApiInfo())
.select()
//匹配特定的路径请求
.paths(Predicates.and(PathSelectors.regex("/admin/.*")))
.build();
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title("xxx后台管理系统API文档")
.description("本文档描述了xxx后台管理系统的各个模块的接口的调用方式")
.version("1.1")
.contact(new Contact("jack", "http://www.baidu.com", "admin@baidu.com"))
.build();
}
//与上面的bean不同的是,这个注入的bean,在调用接口时要在请求头中要传入token参数
@Bean
public Docket webApiConfig(){
List<Parameter> pars = new ArrayList<Parameter>();
//参数构造器
ParameterBuilder tokenPar = new ParameterBuilder();
//构造类型为header的token参数
tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.and(PathSelectors.regex("/api/.*")))
.build()
.globalOperationParameters(pars);//设置为全局参数
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("xxx网站API文档")
.description("本文档描述了xxx网站各个模块的接口的调用方式")
.version("1.1")
.contact(new Contact("jack", "http://baidu.com", "admin@baidu.com"))
.build();
}
}
测试效果