Swagger简明教程
一、什么是swagger
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger让部署管理和使用功能强大的API变得非常简单。
简单来说,就是后端给前端提供的一个可以查看各种接口的方法、类型等。
二、配置swagger
1、pom.xml
1 <!-- swagger2模块 -->
2 <dependency>
3 <groupId>io.springfox</groupId>
4 <artifactId>springfox-swagger-ui</artifactId>
5 <version>2.9.2</version>
6 </dependency>
7 <dependency>
8 <groupId>io.springfox</groupId>
9 <artifactId>springfox-swagger2</artifactId>
10 <version>2.9.2</version>
11 </dependency>
2、Swagger2Config类
在src/main/java/com/example/demo/config目录下新建Swagger2Config类
1 /**
2 * Swagger2Configuration配置类
3 */
4 @Configuration
5 @EnableSwagger2
6 public class Swagger2Config {
7 }
3、Docket方法
源码
1 this.apiInfo = ApiInfo.DEFAULT; //用于定义api文档汇总信息
2 this.groupName = "default";
3 this.enabled = true;
4 this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
5 this.applyDefaultResponseMessages = true;
6 this.host = "";
7 this.pathMapping = Optional.absent();
8 this.apiSelector = ApiSelector.DEFAULT;
9 this.enableUrlTemplating = false;
10 this.vendorExtensions = Lists.newArrayList();
11 this.documentationType = documentationType;
调用
1 @Bean
2 public Docket createApi(){
3 return new Docket(DocumentationType.SWAGGER_2)
4 .apiInfo(apiInfo())
5 //配置分组
6 .groupName("user")
7 //配置是否启动
8 .enable(ture)
9 .select()
10 /**
11 RequestHandlerSelectors:配置要扫描接口的方式
12 basePackage:指定要扫描的包
13 any():扫描全部
14 none():不扫描
15 withClassAnnotation:扫描类上的注解
16 withMethodAnnotation:扫描方法上的注解
17 **/
18 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
19 //path():过滤的路径
20 //.path(PathSelectors.ant("/xxx/*"))
21 .build();
22 }
4、ApiInfo方法
源码
1 public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
2 public static final ApiInfo DEFAULT;
3 private final String version; //文档版本号
4 private final String title; //文档页标题
5 private final String description; //详细信息
6 private final String termsOfServiceUrl; //网站地址
7 private final String license;
8 private final String licenseUrl;
9 private final Contact contact; //联系人信息
10 private final List<VendorExtension> vendorExtensions;
调用
1 private ApiInfo apiInfo(){
2 return new ApiInfoBuilder()
3 .title("Swagger2")
4 .description("RestFul API接口")
5 .version("1.0")
6 .build();
7 }
5、页面效果
http://localhost:8080/swagger-ui.html
groupName可以进行分组以区分后端开发者,如果有多个后端开发者,可以在Swagger2Config类里写多个Docket对象然后通过@Bean注入,不同的Docket对象代表不同的分组
1 @Bean
2 public Docket createApi1(){
3 return new Docket(DocumentationType.SWAGGER_2)
4 .apiInfo(apiInfo())
5 //配置分组
6 .groupName("user1") //user1分组
7 //配置是否启动
8 .enable(ture)
9 .select()
10 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
11 .build();
12 }
13
14 @Bean
15 public Docket createApi2(){
16 return new Docket(DocumentationType.SWAGGER_2)
17 .apiInfo(apiInfo())
18 //配置分组
19 .groupName("user2") //user2分组
20 //配置是否启动
21 .enable(ture)
22 .select()
23 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
24 .build();
25 }
三、Swagger常用注解
1、@ApiModel
使用场景:在实体类上使用,标记类时swagger的解析类
概述:提供有关swagger模型的其它信息,类将在操作中用作类型时自动内省
1 String value() default "";
2
3 String description() default "";
4
5 Class<?> parent() default Void.class;
6
7 String discriminator() default "";
8
9 Class<?>[] subTypes() default {};
10
11 String reference() default "";
属性名称 | 数据类型 | 默认值 | 说明 |
---|---|---|---|
value | String | 类名 | 为模型提供备用名称 |
description | String | "" | 提供详细的类描述 |
parent | Class<?> parent() | Void.class | 为模型提供父类以运行描述继承关系 |
discriminator | String | "" | 支持模型继承和多态,使用鉴别器的字段名称,可以断言需要使用哪个子类型 |
subTypes | Class<?>[] | {} | 从模型继承的子类型数组 |
reference | String | "" | 指定对应类型定义的引用,覆盖指定的任何其他元数据 |
示例
1 /**
2 * Student类 学生实体类
3 */
4 @ApiModel(value = "Student",description = "用户实体类")
5 public class Student implements Serializable {
6 }
2、@ApiModelProperty
使用场景:使用在被 @ApiModel 注解的模型类的属性上。表示对model属性的说明或者数据操作更改
概述:添加和操作模型属性的数据
1 String value() default "";
2
3 String name() default "";
4
5 String allowableValues() default "";
6
7 String access() default "";
8
9 String notes() default "";
10
11 String dataType() default "";
12
13 boolean required() default false;
14
15 int position() default 0;
16
17 boolean hidden() default false;
18
19 String example() default "";
20
21 /** @deprecated */
22 @Deprecated
23 boolean readOnly() default false;
24
25 ApiModelProperty.AccessMode accessMode() default ApiModelProperty.AccessMode.AUTO;
26
27 String reference() default "";
28
29 boolean allowEmptyValue() default false;
30
31 Extension[] extensions() default {@Extension(
32 properties = {@ExtensionProperty(
33 name = "",
34 value = ""
35 )}
36 )};
属性名称 | 数据类型 | 默认值 | 说明 |
---|---|---|---|
value | String | "" | 属性简要说明 |
name | String | "" | 重写属性名称 |
allowableValues | String | "" | 限制参数可接收的值,三种方法,固定取值,固定范围 |
access | String | "" | 过滤属性 |
notes | String | "" | 目前尚未使用 |
dataType | String | "" | 参数的数据类型,可以是类名或原始数据类型,此值将覆盖从类属性读取的数据类型 |
required | boolean | false | 是否为必传参数(false:非必传参数;true:必传参数) |
position | int | "" | 运行在模型中显示排序属性 |
hidden | boolean | false | 隐藏模型属性(false:不隐藏;true:隐藏) |
example | String | "" | 属性的示例值 |
readOnly | boolean | false | 指定模型属性为只读(false:非只读;true:只读) |
reference | String | "" | 指定对应类型定义的引用,覆盖指定的任何其他元数据 |
allowEmptyValue | boolean | false | 运行穿空值(false:不允许传空值;true:运行传空值) |
extensions | Extension[] | {@Extension(properties={@ExtensionProperty(name = "",value = "")})}; | 关联注解 |
示例
1 @ApiModelProperty(value = "学号")
2 private Integer id; //学号
3 @ApiModelProperty(value = "姓名")
4 private String name; //姓名
5 @ApiModelProperty(value = "成绩")
6 private Integer score; //成绩
7 @ApiModelProperty(value = "籍贯")
8 private String birthplace; //籍贯
9 //日期的格式 年-月-日
10 @ApiModelProperty(value = "生日")
11 @DateTimeFormat(pattern = "yyyy-MM-dd")
12 private Date birthday; //生日
3、@ApiOperation
使用场景:使用在方法上,表示一个http请求的操作
概述:用来表示Controller类下的http请求方法
1 String value();
2
3 String notes() default "";
4
5 String[] tags() default {""};
6
7 Class<?> response() default Void.class;
8
9 String responseContainer() default "";
10
11 String responseReference() default "";
12
13 String httpMethod() default "";
14
15 /** @deprecated */
16 @Deprecated
17 int position() default 0;
18
19 String nickname() default "";
20
21 String produces() default "";
22
23 String consumes() default "";
24
25 String protocols() default "";
26
27 Authorization[] authorizations() default {@Authorization("")};
28
29 boolean hidden() default false;
30
31 ResponseHeader[] responseHeaders() default {@ResponseHeader(
32 name = "",
33 response = Void.class
34 )};
35
36 int code() default 200;
37
38 Extension[] extensions() default {@Extension(
39 properties = {@ExtensionProperty(
40 name = "",
41 value = ""
42 )}
43 )};
44
45 boolean ignoreJsonView() default false;
属性名称 | 数据类型 | 默认值 | 说明 |
---|---|---|---|
value | String | 属性简要说明 | |
notes | String | "" | 备注说明 |
tags | String | {""} | 可重新分组 |
response | Class<?> response() | Void.class | 用于描述消息有效负载的可选响应类,对应于响应消息对象的 schema 字段 |
responseContainer | String | "" | 声明响应的容器,有效值为List,Set,Map,任何其他值都将被忽略 |
responseReference | String | "" | 声明响应的引用 |
httpMethod | String | "" | http请求方式 |
position | int | 0 | 运行在模型中显示排序属性 |
nickname | String | "" | 昵称 |
produces | String | "" | For example, "application/json, application/xml" |
consumes | String | "" | For example, "application/json, application/xml" |
protocols | String | "" | Possible values: http, https, ws, wss. |
authorizations | Authorization[] | {@Authorization("")} | 高级特性认证时配置 |
hidden | boolean | false | 是否隐藏 |
responseHeaders | ResponseHeader[] | {@ResponseHeader(name = "",response = Void.class)}; | 可能响应的 header 列表 |
code | int | 200 | http状态码 |
extensions | Extension[] | {@Extension(properties = {@ExtensionProperty(name = "",value = "")})}; | 关联注解 |
ignoreJsonView | boolean | false | 是否忽略json视图 |
示例
1 @ApiOperation("添加学生信息")
2 @PostMapping(value = "/student")
3 public void AddStudent(Student student) {
4
5 studentService.AddStudent(student);
6 }
4、@ApiParam
使用场景:在 Rest 接口上或 Rest 接口参数前边使用
概述:为 Rest 接口参数添加其它元数据(导入到 yapi 中不会被解析)
1 String name() default "";
2
3 String value() default "";
4
5 String defaultValue() default "";
6
7 String allowableValues() default "";
8
9 boolean required() default false;
10
11 String access() default "";
12
13 boolean allowMultiple() default false;
14
15 boolean hidden() default false;
16
17 String example() default "";
18
19 Example examples() default @Example({@ExampleProperty(
20 mediaType = "",
21 value = ""
22 )});
23
24 String type() default "";
25
26 String format() default "";
27
28 boolean allowEmptyValue() default false;
29
30 boolean readOnly() default false;
31
32 String collectionFormat() default "";
属性名称 | 数据类型 | 默认值 | 说明 |
---|---|---|---|
name | String | "" | 参数名称,参数名称将从 filed/method/parameter 名称中派生,但你可以覆盖它,路径参数必须始终命名为它们所代表的路径部分 |
value | String | "" | 参数简单描述 |
defaultValue | String | "" | 描述参数默认值 |
allowableValues | String | "" | 可接收参数值限制,有三种方式,取值列表,取值范围 |
required | boolean | false | 是否为必传参数(false:非必传; true:必传) |
access | String | "" | 参数过滤 |
allowMultiple | boolean | false | 指定参数是否可以通过多次出现来接收多个值 |
hidden | boolean | false | 隐藏参数列表中的参数 |
example | String | "" | 非请求体(body)类型的单个参数示例 |
examples | Example | @Example({@ExampleProperty(mediaType = "",value = "")}); | 参数示例,仅适用于请求体类型的请求 |
type | String | "" | 添加覆盖检测到类型的功能 |
format | String | "" | 添加提供自定义format格式的功能 |
allowEmptyValue | boolean | false | 添加将格式设置为空的功能 |
readOnly | boolean | false | 添加被指定为只读的能力 |
collectionFormat | String | "" | 添加使用 array 类型覆盖 collectionFormat 的功能 |
示例
1 @ApiOperation("判断验证码是否正确")
2 @RequestMapping(value = "/UpdatePassword" , method = RequestMethod.POST)
3 public CommonResult updatePassword(
4 @ApiParam(value = "手机号码",required = true) @RequestParam String userPhone,
5 @ApiParam(value = "验证码",required = true) @RequestParam String authCode){
6
7 return userMemberService.updatePassword(userPhone,authCode);
8 }
5、页面效果
1.@ApiModel与@ApiModelProperty效果
2.@ApiOperation效果
四、导出swagger接口文档
1、导入模块依赖
pom.xml文件
1 <!-- swagger2markup模块 -->
2 <dependency>
3 <groupId>io.github.swagger2markup</groupId>
4 <artifactId>swagger2markup</artifactId>
5 <version>1.3.1</version>
6 </dependency>
2、新增测试类
在src/test/java/com/example/demo目录下新建测试类SwaggerTo
SwaggerTo
1 @RunWith(SpringRunner.class) //测试类要使用注入的类
2 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) //用于单元测试
3 public class SwaggerTo {
4 }
3、新增测试方法
generateMarkdownDocs()
1 /**
2 * 生成Markdown格式文档
3 * @throws Exception
4 */
5 @Test
6 public void generateMarkdownDocs() throws Exception {
7 // 输出Markdown格式
8 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
9 .withMarkupLanguage(MarkupLanguage.MARKDOWN) //输出格式:ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10 .withOutputLanguage(Language.ZH) //语言类型:中文(ZH) 默认英文(EN)
11 .withPathsGroupedBy(GroupBy.TAGS) //Api排序规则
12 .withGeneratedExamples()
13 .withoutInlineSchema()
14 .build();
15
16 Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs?group=user")) //url,注意端口号与分组
17 .withConfig(config)
18 .build()
19 .toFolder(Paths.get("src/docs/markdown/generated")); //生成文件的存放路径,生成多个文件
20 }
此时在src/docs/markdown/generated目录下就会生成definitions.md、overview.md、paths.md、security.md文件,即生成的markdown文件
generateMarkdownDocsToFile()
1 /**
2 * 生成Markdown格式文档,并汇总成一个文件
3 * @throws Exception
4 */
5 @Test
6 public void generateMarkdownDocsToFile() throws Exception {
7 // 输出Markdown到单文件
8 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
9 .withMarkupLanguage(MarkupLanguage.MARKDOWN) //输出格式:ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10 .withOutputLanguage(Language.ZH) //语言类型:中文(ZH) 默认英文(EN)
11 .withPathsGroupedBy(GroupBy.TAGS) //Api排序规则
12 .withGeneratedExamples()
13 .withoutInlineSchema()
14 .build();
15
16 Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs?group=user")) //url,注意端口号与分组
17 .withConfig(config)
18 .build()
19 .toFile(Paths.get("src/docs/markdown/generated/all")); //生成文件的存放路径,汇总为一个文件
20 }
此时在src/docs/markdown/generated目录下就会生成all.md文件,即生成的markdown文件
注意:
如果在Swagger2Config类里声明了分组,即Docket方法有.groupName("user"),那么测试方法中url路径后面需要添加?group=user。如果Swagger2Config类中未声明分组,则测试方法中url路径不需要添加?group=user
在使用测试方法生成文件的时候需要关闭项目,否则会提示端口被占用
可以修改Swagger2MarkupConfig.withMarkupLanguage()方法内的参数值来生成不同的文件格式,修改Swagger2MarkupConverter.toFile()方法内的参数值提供对应的生成文件存放路径
definitions.md存放Models相关信息,overview.md存放文档概览相关信息,paths.md存放controller相关信息,security.md存放与身份认证相关的信息
4、导出文档部分内容
all.md
Swagger简明教程的更多相关文章
- 2013 duilib入门简明教程 -- 第一个程序 Hello World(3)
小伙伴们有点迫不及待了么,来看一看Hello World吧: 新建一个空的win32项目,新建一个main.cpp文件,将以下代码复制进去: #include <windows.h> #i ...
- 2013 duilib入门简明教程 -- 部分bug (11)
一.WindowImplBase的bug 在第8个教程[2013 duilib入门简明教程 -- 完整的自绘标题栏(8)]中,可以发现窗口最大化之后有两个问题, 1.最大化按钮的样式 ...
- 2013 duilib入门简明教程 -- 部分bug 2 (14)
上一个教程中提到了ActiveX的Bug,即如果主窗口直接用变量生成,则关闭窗口时会产生崩溃 如果用new的方式生成,则不会崩溃,所以给出一个临时的快速解决方案,即主窗口 ...
- 2013 duilib入门简明教程 -- 自绘控件 (15)
在[2013 duilib入门简明教程 -- 复杂控件介绍 (13)]中虽然介绍了界面设计器上的所有控件,但是还有一些控件并没有被放到界面设计器上,还有一些常用控件duilib并没有提供(比如 ...
- 2013 duilib入门简明教程 -- 事件处理和消息响应 (17)
界面的显示方面就都讲完啦,下面来介绍下控件的响应. 前面的教程只讲了按钮和Tab的响应,即在Notify函数里处理.其实duilib还提供了另外一种响应的方法,即消息映射DUI_BEG ...
- 2013 duilib入门简明教程 -- FAQ (19)
虽然前面的教程几乎把所有的知识点都罗列了,但是有很多问题经常在群里出现,所以这里再次整理一下. 需要注意的是,在下面的问题中,除了加上XML属性外,主窗口必须继承自WindowImpl ...
- Mac安装Windows 10的简明教程
每次在Mac上安装Windows都是一件非常痛苦的事情,曾经为了装Win8把整台Mac的硬盘数据都弄丢了,最后通过龟速系统恢复模式恢复了MacOSX(50M电信光纤下载了3天才把系统下载完),相信和我 ...
- Docker简明教程
Docker简明教程 [编者的话]使用Docker来写代码更高效并能有效提升自己的技能.Docker能打包你的开发环境,消除包的依赖冲突,并通过集装箱式的应用来减少开发时间和学习时间. Docker作 ...
- 2013 duilib入门简明教程 -- 总结 (20)
duilib的入门系列就到尾声了,再次提醒下,Alberl用的duilib版本是SVN上第个版本,时间是2013.08.15~ 这里给出Alberl最后汇总的一个工程,戳我下载,效 ...
随机推荐
- 【ProLog - 3.0 进阶:递归】
[ProLog中的递归] 如果递归中的一个或多个规则引用谓词本身,则对该谓词使用"递归"定义 在使用时,这往往像一条食物链或者族谱的构成(A的爸爸的爸爸,即A的爷爷,是A的长辈) ...
- 用递归求n皇后问题
此问题是指在n*n的国际象棋棋盘上 ,放置n个皇后,使得这n个皇后均不在,同一行,同一列,同一对角线上,求出合法的方案的数目. 本题可以简单转化为就是求n的全排列中的数放在棋盘上使得这几组数,符合均不 ...
- Lucas(卢卡斯)定理
Lucas(卢卡斯)定理 定义 若 \(p\) 为质数,且\(a\ge b\ge1\),则有: \[C_{a}^{b}\equiv C_{a/p}^{b/p}\cdot C_{a (mod\,p)}^ ...
- ASP.NET Core扩展库之Http通用扩展
本文将介绍Xfrogcn.AspNetCore.Extensions扩展库对于Http相关的其他功能扩展,这些功能旨在处理一些常见需求, 包括请求缓冲.请求头传递.请求头日志范围.针对HttpClie ...
- day17.网络编程2+进程
1 加入链接循环的套接字服务端 1.1 服务端 ''' 2.1 基于文件类型的套接字家族 套接字家族的名字:AF_UNIX unix一切皆文件,基于文件的套接字调用的就是底层的文件系统来取数据,两个套 ...
- Ubuntu 快速安装Gitlab-ce
1.下载并安装gitlab,下载地址: https://packages.gitlab.com/gitlab/gitlab-ce/ sudo dpkg -i gitlab-ce_12.0.3-ce.0 ...
- linux下安装并使用msgfmt命令
msgfmt安装方法: sudo apt-get install gettext 编码 po 文件为 mo 文件: msgfmt -o test.mo test.po mo 文件反编码成 po文件: ...
- OPPO R11S识别不到ADB Device
1.手机开启[开发者选项] 2.[开发者选项]打开[USB调试] 有个坑:10分钟不使用,将自动关闭 3.USB连接到电脑,选择模式为[仅充电] 4.电脑安装OPPO驱动 坑:安装进度卡在95%三分钟 ...
- 【MySQL】若sql语句中order by指定了多个字段,则怎么排序?
举个例子吧:order by id desc,time desc先是按 id 降序排列 (优先)如果 id 字段 有些是一样的话 再按time 降序排列 (前提是满足id降序排列) order b ...
- 【CompletableFuture】CompletableFuture中join()和get()方法的区别
一.相同点: join()和get()方法都是用来获取CompletableFuture异步之后的返回值 二.区别: 1.join()方法抛出的是uncheck异常(即未经检查的异常),不会强制开发者 ...