Swagger的简介
随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态, 而且前端技术和后端技术在各自的道路上越走越远。前端和后端的唯一联系,变成了API接口;API文档变成 了前后端开发人员联系的纽带,变得越来越重要,swagger 就是一款让你更好的书写 API 文档的框架。Swagger 是全球最大的开源 API 开发工具框架,支持从设计到测试和部署的整个 API 生命周期的开发。 Swagger的出现就是为了方便进行测试后台的 restful(restful 是一种推荐的规范,该规范使用 put、post、get、delete 等指代增、改、查和删等)形式的接口,实现动态的更新,当我们在后台的接口修改了后,Swagger可以实现自动的更新,可以给前端人员提供自动测试方法
整合Swagger2的步骤
在SpringBoot项目的pom.xml文件中引入依赖
< ! -- Swagger2 -- >
< dependency>
< groupId> io. springfox< / groupId>
< artifactId> springfox- swagger2< / artifactId>
< version> 2.6 .1 < / version>
< / dependency>
< dependency>
< groupId> io. springfox< / groupId>
< artifactId> springfox- swagger- ui< / artifactId>
< version> 2.6 .1 < / version>
< / dependency>
常用注解 描述 @Api 修饰整个类,描述 Controller 的作用 @ApiOperation 描述一个类的一个方法,或者说一个接口 @ApiParam 单个参数描述 @ApiModel 描述实体类 @ApiModelProperty 描述实体类属性 @ApiProperty 用对象接收参数时,描述对象的一个字段 @ApiResponse HTTP 响应其中 1 个描述 @ApiResponses HTTP 响应整体描述 @ApiIgnore 使用该注解忽略这个 API @ApiError 发生错误返回的信息 @ApiImplicitParam 一个请求参数 @ApiImplicitParams 多个请求参数
编写Swagger配置类Swagger2,扫描SpringMVC控制器
import org. springframework. context. annotation. Bean;
import org. springframework. context. annotation. Configuration;
import springfox. documentation. builders. ApiInfoBuilder;
import springfox. documentation. builders. PathSelectors;
import springfox. documentation. builders. RequestHandlerSelectors;
import springfox. documentation. service. ApiInfo;
import springfox. documentation. spi. DocumentationType;
import springfox. documentation. spring. web. plugins. Docket;
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi ( ) {
return new Docket ( DocumentationType. SWAGGER_2)
. apiInfo ( apiInfo ( ) )
. select ( )
. apis ( RequestHandlerSelectors. basePackage ( "com.rx.controller" ) )
. paths ( PathSelectors. any ( ) )
. build ( ) ;
}
private ApiInfo apiInfo ( ) {
return new ApiInfoBuilder ( )
. title ( "springboot 利用 swagger 构建 api 文档" )
. description ( "简单优雅的 restful 风格" )
. termsOfServiceUrl ( "https://blog.csdn.net/Xu_Ren/article/details/105059039" )
. version ( "1.0" )
. build ( ) ;
}
}
在启动类上,加上注解@EnableSwagger2
来开启 Swagger 启动 SpringBoot 项目,测试路径:http://localhost:8080/swagger-ui.html