一、Swagger
1、什么是 Swagger ?
Swagger 是一个规范和完整的框架,用于生成、描述、调用以及可视化的 Restful 风格的 Web 服务。
简单的理解:是一款 REST API 文档生成工具,生成在线的接口文档,方便接口测试。
2、为什么使用 Swagger?
前后端分离开发时,为了方便前后端接口调用规范,需要提供一个接口文档,但是维护这个接口文档是一个及其繁琐的事情,可能一不小心就忘记更新该文档从而导致前后端接口调用失败。
Swagger 就是为了解决这个问题而出现的(在线接口文档),其在接口方法上定义注解,并根据注解形成一个 html 页面,每次接口修改,这个 html 页面就会发生相应的改变,从而保证了接口文档的正确性。通过该 html 页面,可以很方便、清楚的知道这个接口的功能,并测试。
3、SpringBoot 整合 Swagger?
(1)Step1:
导入依赖 jar 包。
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
(2)Step2:
配置 swagger 插件。
编写一个配置类,实现 WebMvcConfigurer 接口(可以不实现该接口),用于配置 Swagger 相关信息。
@EnableSwagger2 用于开启 Swagger。
packagecom.lyh.test.test_mybatis_plus.config;importio.swagger.annotations.ApiOperation;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importspringfox.documentation.builders.ApiInfoBuilder;importspringfox.documentation.builders.PathSelectors;importspringfox.documentation.builders.RequestHandlerSelectors;importspringfox.documentation.service.ApiInfo;importspringfox.documentation.spi.DocumentationType;importspringfox.documentation.spring.web.plugins.Docket;importspringfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2public class SwaggerConfig implementsWebMvcConfigurer {
@BeanpublicDocket createRestApi() {return newDocket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()//加了ApiOperation注解的类,才会生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//指定包下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
.paths(PathSelectors.any())
.build();
}privateApiInfo apiInfo() {return newApiInfoBuilder()
.title("Swagger 测试")
.description("Swagger 测试文档")
.termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
.version("1.0.0")
.build();
}
}<