Swagger
- 号称世界上最流行的API框架
- RestFul API文档在线自动生成工具 ==》API文档与API定义同步更新
- 直接运行,可以在线测试API接口
- 支持多种语言
1、使用Swagger
在项目中使用Swagger需要Springfox;
- swagger2
- ui
2、springboot集成swagger
- 新建一个springboot web项目
- 导入相关依赖
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- swagger ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 配置swagger,交给springboot
@Configuration //表明这是一个配置类
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
}
- 测试swagger:访问 http://localhost:8080/swagger-ui.html
3、配置swagger的API信息
swagger的bean实例叫做Docket,我们只需要创建一个Docket对象(在该对象中配置一些参数),托管给spring,即完成了我们自定义的swagger
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
//docket对象中的apiInfo属性,对应swagger页面上的文档信息
.apiInfo(info());
}
//docket对象中的aipInfo属性,对应swagger页面上的文档信息
private ApiInfo info() {
//作者信息
Contact DEFAULT_CONTACT = new Contact("戴辰", "", "729229951@qq.com");
return new ApiInfo(
//文档信息的标题
"这是我的日志"
//文档信息的描述
, "日志描述"
//文档信息的版本
, "1.0"
//项目的url
, "localhost:8080"
//文档信息的作者信息
, DEFAULT_CONTACT
, "Apache 2.0"
//作者信息的url
, "http://www.apache.org/licenses/LICENSE-2.0"
, new ArrayList());
}
4、配置swagger的扫描接口
return new Docket(DocumentationType.SWAGGER_2)
//docket对象中的apiInfo属性,对应swagger页面上的文档信息
.apiInfo(info())
.select()
/*
* RequestHandlerSelectors:配置要扫描接口的方式
* .paths(PathSelectors.none()) PathSelectors:配置要过滤哪些接口的方式
*
* basePackage:指定扫描的包
* any:扫描全部
* none:不扫描
* withClassAnnotation:扫描类上的注解,参数是一个注解的.class
* withMethodAnnotation:扫描方法上的注解
* */
//只扫描该包下,所有的api信息
.apis(RequestHandlerSelectors.basePackage("com.maki.controller"))
.build();
}
Tips:.enable(boolean) 可以选择开启,或者关闭swagger
5、根据项目所在环境,动态开启关闭swagger
/*
* swagger的bean实例叫做Docket,该对象中配置了swagger页面上的一些信息
* spring在创建该实例时,会传递一个Environment对象
* 用于获取配置文件中的信息
* */
@Bean
public Docket docket(Environment environment) {
//根据生产环境,动态开启关闭swagger
//设置要显示的swagger环境(获取dev的profile对象)
Profiles profiles = Profiles.of("dev");
//通过Environment.acceptsProfiles,判断是否处在当前设定的环境中
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
//动态开启关闭swagger
.enable(flag)
}
6、配置API文档的分组
//设置组信息
.groupName("Maki")
如何创建多个组?
创建多个Docket对象即可
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("A组");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("B组");
}
7、配置swagger的实体类信息
只要在接口中,返回值中有实体类,他就会被扫描到swagger中
//只要在接口中,返回实体类信息,就可以被扫描到swagger中
//该注解用于说明接口方法
@ApiOperation("这是一个user接口")
@GetMapping("/user")
//ApiParam注解用于说明参数信息
public User user(@ApiParam("这是参数信息") String name){
return new User();
}
8、swagger中的测试功能
这里发生错误,是因为在controller中没有设置为,RestController或者ResponseBody
设置成功后
总结
- 我们可以通过swagger给一些接口或者属性,增加注释信息
- 接口文档实时更新
- 可以在线测试
- 在正式发布时,记得关闭