Swagger2
Swagger简介
前后端分离
- 前端 -> 前端控制层、视图层
- 后端 -> 后端控制层、服务层、数据访问层
- 前后端通过API进行交互
- 前后端相对独立且松耦合
产生的问题
前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发
解决方案
首先定义schema [ 计划的提纲 ],并实时跟踪最新的API,降低集成风险
Swagger
-
号称世界上最流行的API框架
-
Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
-
直接运行,在线测试API
-
支持多种语言 (如:Java,PHP等)
-
官网:https://swagger.io/
SpringBoot集成Swagger
使用Swagger
要求:jdk 1.8 + 否则swagger2无法运行
步骤
-
新建一个SpringBoot-web项目
springboot-07-swagger2
-
添加Maven依赖
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
-
编写HelloController,测试确保运行成功!
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
- 使用Swagger,我们需要编写一个配置类
SwaggerConfig
来配置 Swagger
@Configuration // 配置类
@EnableOpenApi // 开启Swagger2的自动配置
public class SwaggerConfig {
}
- 访问测试 :http://localhost:8080/swagger-ui/index.html ,可以看到swagger的界面
配置Swagger
- Swagger实例Bean是
Docket
,所以通过配置Docket实例来配置Swaggger。
//配置docket以配置Swagger具体参数
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2);
}
- 可以通过
apiInfo()
属性配置文档信息
// 配置swagger信息 apiInfo
private ApiInfo apiInfo() {
Contact contact = new Contact("ChenHYu", "https://gitee.com/chenHYu1120", "626810226@qq.com");
return new ApiInfo(
"Swagger学习", // 标题
"学习演示如何配置Swagger", // 描述
"3.0.0", // 版本
"https://gitee.com/chenHYu1120", // 组织链接
contact, // 联系人信息
"Apache 2.0 许可", // 许可
"http://www.apache.org/licenses/LICENSE-2.0", // 许可连接
new ArrayList<>()// 扩展
);
}
- Docket 实例关联上
.apiInfo()
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2