Swagger学习
学习目标
- 了解swagger的作用和概念
- 了解前后端分离
- 在Springboot中集成swagger
Swagger简介
前后端分离
vue + springboot
后端时代:前端只管理静态页面;html=>后端。引擎模板 JSP =>后端主力
前后端分离时代:
-
后端:后端控制层,服务层,数据访问层【后端团队】
-
前端:前端控制层,视图层【前端团队】
- 伪造后端数据,json。已近存在,不需要后端,前端依旧能跑起来
-
前后端交互?====API
-
前后端相对独立,松耦合
-
前后端甚至可以部署在不同的服务器中
产生的问题:
- 前端集成联调,前端人员无法做到,及时协商,尽早解决,就会导致问题集中爆发
解决方案:
- 首先指定schema【计划的提纲】,实时更新最新的API,降低集成风险
- 早先年指定word计划文档;
- 前后端分离:
- 前端测试后端接口 Postman
- 后端提供接口,需要实时更新最新的消息及改动
Swagger
- 号称世界上最流行的API流行框架
- RestFul Api 文档在线自动生成工具=>Api文档与Api定义同步更新
- 直接运行,可以在线测试Api接口
- 支持多种语言:(java,php,…)
官网:https://swagger.io/
在项目中使用Swagger需要springbox;
- swagger2
- ui
Springboot 集成Swagger
1.创建一个spring的项目(web项目)
2.导入相关依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
3.编写一个Hello工程
4.swagger==>config
@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
}
5.测试运行,
6、生产环境才显示
@Bean
public Docket docket(Environment environment){
//获取项目环境---发布+生产
//设置什么环境下显示swagger
Profiles profiles = Profiles.of("dev","test");
//通过environment.acceptsProfiles判断是否处在自己设定的环境当中
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(flag) //dev test 启动swagger,其他环境不开启swagger
.select()
.apis(RequestHandlerSelectors.basePackage("com.carter.controller"))
.build();
}