学习视频: https://www.bilibili.com/video/BV1PE411i7CV?p=47
1.1 Swagger基本概念
Swagger官网:https://swagger.io/
前后端分离
- 后端:后端控制层,服务层,数据访问层。
- 前端: 前端控制层、视图层。
- 前后端通过API进行交互,前后端相对独立且松耦合。
- 前后端可以部署在不同的服务器上…
产生的问题
前后端集成联调,前端人员和后端人员无法做到"即使协商,尽早解决",最终导致问题集中爆发。
解决方案:
- 指定schema【计划的提纲】,实时更新最新的API,降低集成的风险。
Swagger
- 号称世界上最流行的API框架。
- Restful Api 文档在线自动生成器,API 文档 与API 定义同步更新。
- 直接运行,在线测试API,支持多种语言 (如:Java,PHP等)。
1.2 集成Swagger
1、新建一个Springboot项目。
2、添加相关的maven依赖
2.x.x 版本
<!-- 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>
3.x.x版本
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
3、编写对应的controller
package cn.guardwhy.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value = "/hello")
public String hello(){
return "hello Swagger!!!";
}
}
4、编写一个配置类-SwaggerConfig来配置 Swagger
package cn.guardwhy.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration // 配置类