Swagger
- 号称世界上最流行的API框架
- Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
- 直接运行,在线测试API
- 支持多种语言 (如:Java,PHP等)
- 官网:https://swagger.io/
1.SpringBoot集成Swagger
①新建一个SpringBoot项目
②添加Maven依赖
<!-- 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>
③ 编写HelloController,测试确保运行成功
④ 编写一个配置类-SwaggerConfig来配置 Swagger
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {
}
⑤访问测试 :http://localhost:8080/swagger-ui.html
2.配置Swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//配置了Swagger的Docket的bean实例
@Bean
public Docket docket(Environment environment){
//当前环境
Profiles profiles = Profiles.of("dev");
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//设置分组
.groupName("lit")
//设置是否启用swagger
.enable(flag)
.select()
//RequestHandlerSelectors 配置要扫描的接口
//basePackage 指定要扫描的包
//any() 扫描全部
//none() 不扫描
//withClassAnnotation() 扫描类上的注解 参数是一个注解的反射对象
//withMethodAnnotation() 扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.lit.Controller"))
//path() 过滤什么路径
.paths(PathSelectors.ant("/lit/**"))
.build();
}
//配置Swagger信息 apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("name","https://www.baidu.com","123456@qq.com");
/**
* @Deprecated
* public ApiInfo(String title,
* String description,
* String version,
* String termsOfServiceUrl,
* String contactName,
* String license,
* String licenseUrl)
*/
return new ApiInfo("title","描述","版本","链接",contact,"","",new ArrayList<>());
}
}
3.常用注解
Swagger的所有注解定义在io.swagger.annotations包下
下面列一些经常用到的,未列举出来的可以另行查阅说明:
Swagger注解 | 简单说明 |
---|---|
@Api(tags = “xxx模块说明”) | 作用在模块类上 |
@ApiOperation(“xxx接口说明”) | 作用在接口方法上 |
@ApiModel(“xxxPOJO说明”) | 作用在模型类上:如VO、BO |
@ApiModelProperty(value = “xxx属性说明”,hidden = true) | 作用在类方法和属性上,hidden设置为true可以隐藏该属性 |
@ApiParam(“xxx参数说明”) | 作用在参数、方法和字段上,类似@ApiModelProperty |