目标:
- 了解Swagger的作用和概念
- 了解前后端分离
- 在SpringBoot中集成Swagger
Swagger简介
前后端分离
Vue+SpringBoot
后端时代:前端只用管理静态页面;html==>后端。模板引擎JSP=>后端是主力
现在属于前后端分离时代:
- 后端:后端控制层Controller,服务层Service,数据访问层Dao【后端团队】
- 前端:前端控制层例如Vue vm-的对象,视图层【前端团队】
- 伪造后端数据,Json。已经存在了,不需要后端,前端工程依旧能够跑起来。
- 前后端如何交互?====>API
- 前后端相对独立,松耦合;
- 前后端甚至可以部署在不同的服务器上;
产生一个问题:
- 前后端集成联调,前端人员和后端人员无法做到及时协商,尽早解决,最终导致问题集中爆发;
解决方案:
- 首先制定schema[计划的提纲],实时更新最新的API,降低集成的风险;
- 早先年:制定word计划文档;
- 前后端分离:
- 前端测试后端接口:Postman
- 后端提供接口,需要实时更新最新的消息及改动!
Swagger
- 号称世界上最流行的Api框架;
- RestFul Api文档在线自动生成工具=>Api文档与API定义同步更新
- 直接运行,可以在线测试API接口;
- 支持多种语言:(Java,php)
在项目中使用Swagger需要springbox;
- swagger2
- ui
SpringBoot集成Swagger
1、新建一个Spring-Web项目
在Maven中搜索 springfox-swag
https://mvnrepository.com/search?q=springfox-swag
新建一个项目
最后finish。
2、导入相关依赖 3.0.0 降级成2.9.2 的jar包否则预览不了
<!-- 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、编写一个Hello工程
4、配置Swagger=>Config pom.xml中 3.0.0 降级成2.9.2 的jar包否则预览不了
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
5、测试运行:http://localhost:8080/swagger-ui.html
配置Swagger
Swagger的bean实例Docket;
package com.kuang.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration //等价于 @Component
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置了Swagger的Docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
//配置Swagger信息=apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("周树人", "https://blog.edjoke.com", "565036413@qq.com");
return new ApiInfo(
"鲁迅的狂人日记SwaggerAPI文档",
"即使再小的帆也能远航",
"v1.0",
"https://blog.edjoke.com/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}