1.Swagger概述
Swagger 是一个规范完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。主要功能有:
A. 使得前后端分离开发更加方便,有利于团队协作
B. 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担
C. 接口功能测试
Spring Boot 可以集成Swagger,生成Swagger接口,并生成接口文档, 进行接口测试 。
2.Swagger使用步骤
A. 引入依赖
直接在项目中引入依赖
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
B. 添加配置类
在项目中添加配置类(配置类需要在引导类所在包的子包下,否则需要单独导入)
package com.xs.swagger;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xs"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("小许好楠项目")
.description("后端接口-API文档")
.version("1.0")
.build();
}
}
C. 访问接口文档
A. 查看接口文档
http://localhost:8080/swagger-ui.html
8080改为自己服务器的端口号
B. 接口测试
3.Swagger常用注解
在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下:
注解 | 含义 | 备注 |
---|---|---|
@Api | 修饰整个类 , 描述Controller的作用 | |
@ApiOperation | 描述一个类的一个方法, 或者说一个接口 | |
@ApiParam | 单个参数描述 | |
@ApiModel | 用对象接收参数 | |
@ApiModelProperty | 用对象接收参数时, 描述对象的属性 | |
@ApiResponse | HTTP响应其中1个描述 | |
@ApiResponses | HTTP响应的整个描述 | |
@ApiIgnore | 使用该注解忽略这个API接口 | |
@ApiError | 发生错误返回的信息 | |
@ApiImplicitParam | 一个请求参数 | |
@ApiImplicitParams | 多个请求参数 |