一: 简介
什么是swagger ?
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。目前来说swagger一共有两个版本,且区别还挺大,第一个版本就是swagger-ui也就是swagger1;第二个版本是springfox-swagger也就是swagger2;
本篇只说Swagger2在线文档框架,因为相对swagger1来说,本人觉得使用swagger2开发效率更好,且使用更方便,它是通过注解的方式生成在线文档,不同于swagger1 还需写index.xml和ymal配置文件。
为什么要用swagger ?
因为自前后端分离后,写接口文档可以说是必不可少得工作。我们在理想状态下,只需设计好接口文档,然后通过前/后端小伙伴按规则开发,开发好之后对接上线就OK了,当然,这样的流程仅限于理想状态,而在实际开发过程中,我们只能不断的 改丶改丶 改 [ 就问你炸不炸 ] ,所以我们如何“优雅”的写接口文档呢?使用swagger就是其中一种方式,这里只介绍swagger2。
下面开始 SpringBoot + Maven + Swagger2 的使用
二:集成,测试
一:添加依赖
<!--引入swagger2依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
二:swagger2信息配置
创建一个Swagger2Config类 用于swagger的基本配置(自定义命名,想咋写咋写)
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 对Swagger2的配置信息
*
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGE