SpringBoot 整合Swagger
前后端分离:
问题:
前后端集成联调,前后端难以做到“及时协调”,矛盾出现
解决:
指定schema[计划提纲],及时更新最新api,降低集成的风险
前端:postman
后端:提供接口,需要实时更新最新的消息及其改动
简介:
号称世界上最流行的Api框架
RestFul Api 文档在线自动生成工具 => api文档和api定义在线同步进行更新
直接运行,可以在线测试api接口
支持多种语言:(java、PHP)
简单进行配置后使用相关注解即可进行使用
依赖:
<!-- 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>
<!--新增解决 parameter type integer 报错的配置 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
配置SwaggerConfig:
配置后
效果:baseUrl/swagger-ui.html
运行后即可打开:
配置:
Swagger的bean实例Docket:
其实主要信息也就标题和描述而已
配置扫描接口:
设置ApiInfo(*).enable(false)后效果:
😱 Could not render e, see the console.
Docket.select()
.build();
设置swagger在项目环境中可使用,在生产上线时关闭
设置多个yml配置文件,在主yml中通过spring.profiles.active来设置要启动的yml(注意下yml的命名格式)
然后再配置文件SwaggerConfig中来监听当前环境即可
//获取当前项目的环境,以便管理swagger的开闭
Profiles profiles = Profiles.of("dev","test"); //接口方法的实现类
//通过environment.acceptsProfiles判断当前环境是否处在自己所设定的环境中
Boolean flag = environment.acceptsProfiles(profiles);
//设置api文档的分组
.groupName("良夜")
设置多个api文档的分组---设置多个Docket实例后托管于SpringBoot即可
实体类配置:
@ApiModel
@ApiModelProperty --属性注释, 如
注意: 有时候属性用了注解@ApiModelProperty但未给默认值可能会报错
@ApiModelProperty(value = "设为自增", example = "1") //value为注解,exampe为对应属性的默认值
private Integer id; //设为自增
Controller配置:
@Api (tags = "") ##不建议去使用
@ApiOperation --放在方法上,用于注释方法
@ApiParams --注释方法参数
总结:
可以通过swagger给一些比较难以理解的属性或者方法加一些注解
接口文档实时更新
可以在线测试
注意:出于安全考虑,在项目正式发布的时候,需要关闭swagger,且可以节省内存 --即上面所讲的判断当前的项目环境即可