------------------------------Swagger(丝袜格儿)----------------------------
学习目标:
·了解Swagger的作用和概念
·了解前后端分离
·在SrpingBoot中集成Swagger
我们可以使用Swagger工具,帮助团队和企业能够更简单的进行用户以及API接口的开发
本文章末尾有源码
------------------------------Swagger简介------------------------------
前后端分离:
Vue+SpringBoot
后端时代:
前端只用管理静态页面;html==>后端。模板引擎 JSP=>后端是主力
前后端分离时代:
·后端:后端控制层(controller),服务层,数据访问层【后端团队】
·前端:前端控制层,视图层【前端团队】
·伪造后端数据,json。已经存在了,不需要后端,前端工程依旧能够跑起来
·前后端如何交互?===>API
·前后端相对独立,松耦合;
·前后端甚至可以部署在不同的服务器上;
产生一个问题:
·前后端集成联调,前端人员和后端人员无法做到,及时协商,尽早解决,最终导致问题集中爆发;
解决方案:
·首先制定一个schema计划的提纲,实时更新最新API,降低集成的风险;
·早先年:制定word计划文档;
·前后端分离:
·前端测试后端接口:postman
·后端提供接口,需要实时更新最新的消息及改动!
--------------------------------Swagger--------------------------------
·号称世界上最流行的API框架
·RestFul Api风格 文档在线自动生成工具=>Api文档与Api定义同步更新
·直接运行,可以在线测试API接口;
·支持多种语言:(Java,Php…);
在项目中使用Swagger 需要springbox;
·swagger2
·swaggerUi
SpringBoot集成Swagger
1.新建一个SpringBoot = Web项目
2.导入相关依赖 Springfox Swagger2和Springfox SwaggerUi
<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工程
package com.can.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// /error
@RequestMapping(value = "/hello")
public String hello(){
return "hello";
}
}
4.配置Swagger==>Config
@Configuration
@EnableSwagger2 // 开启Swagger2
public class SwaggerConfig {
}
5.测试运行:http://localhost:8080/swagger-ui.html
6.配置Swagger
Swagger的bean实例 Docket;
package com.can.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
@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 DEFAULT_CONTACT = new Contact("谢炳灿", "https://me.csdn.net/qq_44619964", "1045857717@qq.com");
return new ApiInfo("Can的SwaggerAPI文档", //标题
"作者的描述", //文档描述
"1.0", //版本
"https://me.csdn.net/qq_44619964", //