Swagger2 视频:https://www.bilibili.com/video/BV1Y441197Lw
官方文档:https://mp.weixin.qq.com/s/0-c0MAgtyOeKx6qzmdUG0w
前后端分离
前端 -> 前端控制层、视图层
后端 -> 后端控制层、服务层、数据访问层
前后端通过API进行交互
前后端相对独立且松耦合
产生的问题
前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发
解决方案
首先定义schema [ 计划的提纲 ],并实时跟踪最新的API,降低集成风险
Swagger
号称世界上最流行的API框架
Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新
直接运行,在线测试API
支持多种语言 (如:Java,PHP等)
官网:https://swagger.io/
SpringBoot集成Swagger
SpringBoot集成Swagger => springfox ,两个jar包
Springfox-swagger2
swagger-springmvc
使用Swagger 要求:jdk 1.8 + 否则swagger2无法运行
步骤:
1、新建一个SpringBoot-web项目
2、添加Maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger-ui</artifactId > <version > 2.9.2</version > </dependency > <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger2</artifactId > <version > 2.9.2</version > </dependency >
3、编写HelloController,测试确保运行成功!
1 2 3 4 5 6 7 8 @RestController public class HelloController { @GetMapping("/hello") public String hello () { return "hello" ; } }
4、要使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger
这是使用swagger2.10.5会出现的问题,之后改用2.9.2 (也有可能是端口错误的原因)
2.10.5在 SwaggerConfig.java 文件加上 @EnableSwagger2WebMvc 此配置,不然使用原有的 @EnableSwagger2 或者使用成 @EnableSwagger2WebFlux 会出现图片出现的错误。
1 2 3 4 5 @Configuration @EnableSwagger2 public class SwaggerConfig { }
如果报错SpringBoot项目中集成了knife4j,在将SpringBoot更新到2.7.2后启动项目报错 Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException,导致系统不能正常启动。
需要在application.properties中田如下配置
1 spring.mvc.pathmatch.matching-strategy =ant_path_matcher
5、访问测试 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面;
配置Swagger 1、Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。
1 2 3 4 @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2); }
2、可以通过apiInfo()属性配置文档信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private ApiInfo apiInfo () { Contact contact = new Contact ("联系人名字" , "http://xxx.xxx.com/联系人访问链接" , "联系人邮箱" ); return new ApiInfo ( "Swagger学习" , "学习演示如何配置Swagger" , "v1.0" , "http://terms.service.url/组织链接" , contact, "Apach 2.0 许可" , "许可链接" , new ArrayList <>() ); }
3、Docket 实例关联上 apiInfo()
1 2 3 4 @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2).apiInfo(apiInfo()); }
完整配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2).apiInfo(apiInfo()); } private ApiInfo apiInfo () { Contact contact = new Contact ("联系人名字" , "http://xxx.xxx.com/联系人访问链接" , "联系人邮箱" ); return new ApiInfo ( "Swagger学习" , "学习演示如何配置Swagger" , "v1.0" , "http://terms.service.url/组织链接" , contact, "Apach 2.0 许可" , "许可链接" , new ArrayList <>() ); } }
4、重启项目,访问测试 http://localhost:8080/swagger-ui.html 看下效果;
配置扫描接口 1、构建Docket时通过select()方法配置怎么扫描接口。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ep.controller" )) .build() ; }
2、重启项目测试,由于我们配置根据包的路径扫描接口,所以我们只能看到一个类
3、除了通过包路径配置扫描接口外,还可以通过配置其他方式扫描接口,这里注释一下所有的配置方式:
1 2 3 4 5 6 7 any() none() withMethodAnnotation(final Class<? extends Annotation > annotation) withClassAnnotation(final Class<? extends Annotation > annotation) basePackage(final String basePackage)
4、除此之外,我们还可以配置接口扫描过滤:
1 2 3 4 5 6 7 8 9 10 @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ep.controller" )) .paths(PathSelectors.ant("/test/*" )) .build(); }
5、这里的可选值还有
1 2 3 4 any() none() regex(final String pathRegex) ant(final String antPattern)
配置Swagger开关 1、通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Bean public Docket docket () { return new Docket (DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(false ) .select() .apis(RequestHandlerSelectors.basePackage("com.ep.controller" )) .paths(PathSelectors.any()) .build() ; }
2、如何动态配置当项目处于test、dev环境时显示swagger,处于prod时不显示?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Autowired private ApplicationContext context; @Bean public Docket docket (Environment environment) { boolean flag; if (context.getEnvironment().getActiveProfiles()[0 ].equals("dev" )){ flag = true ; }else { flag = false ; } return new Docket (DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(flag) .select() .apis(RequestHandlerSelectors.basePackage("com.ep.controller" )) .paths(PathSelectors.any()) .build() ; }
3、可以在项目中增加一个dev的配置文件查看效果!
配置API分组 1、如果没有配置分组,默认是default。通过groupName()方法即可配置分组:
1 2 3 4 5 6 @Bean public Docket docket (Environment environment) { return new Docket (DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .groupName("hello" ) }
2、重启项目查看分组
3、如何配置多个分组?配置多个分组只需要配置多个docket即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Bean public Docket docket1 () { return new Docket (DocumentationType.SWAGGER_2).groupName("A" ); }@Bean public Docket docket2 () { return new Docket (DocumentationType.SWAGGER_2).groupName("B" ); }@Bean public Docket docket3 () { return new Docket (DocumentationType.SWAGGER_2).groupName("C" ); }
4、重启项目查看即可
实体配置 1、新建一个实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;@ApiModel("用户实体类") @Data public class User { @ApiModelProperty(value = "用户名") private String username; @ApiModelProperty(value = "密码") private String password; @ApiModelProperty(value = "年龄") private Integer age; }
2、只要这个实体在请求接口 的返回值上(即使是泛型),都能映射到实体项中:
1 2 3 4 5 @ApiOperation("保存用户") @PostMapping("/user") public User insertUser (User user) { return user; }
3、重启查看测试
注:并不是因为@ApiModel这个注解让实体显示在这里了,而是只要出现在接口方法的返回值上的实体都会显示在这里,而@ApiModel和@ApiModelProperty这两个注解只是为实体添加注释的。
@ApiModel为类添加注释
@ApiModelProperty为类属性添加注释
常用注解 Swagger的所有注解定义在io.swagger.annotations包下
下面列一些经常用到的,未列举出来的可以另行查阅说明:
Swagger注解
简单说明
@Api(tags = “xxx模块说明”)
作用在模块类上,@Api(tags = “Test类”): 用于类上,为该类进行注释,注意参数必须是“tags”才会有效(默认也不行,因为默认是第一个字段value)
@ApiOperation(“xxx接口说明”)
作用在接口方法上
@ApiModel(“xxxPOJO说明”)
作用在模型类上:如VO、BO
@ApiModelProperty(value = “xxx属性说明”,hidden = true)
作用在类方法和属性上,hidden设置为true可以隐藏该属性
@ApiParam(“xxx参数说明”)
作用在参数、方法和字段上,类似@ApiModelProperty
我们也可以给请求的接口配置一些注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import com.ep.pojo.User;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;@Api(tages = "HelloController类") @RestController public class HelloController { @ApiOperation("你好") @GetMapping("/test/hello") public String hello () { return "hello" ; } @GetMapping("/username") public String username (@ApiParam("这个名字会被返回") String username) { return username; } }
这样的话,可以给一些比较难理解的属性或者接口,增加一些配置信息,让人更容易阅读!
相较于传统的Postman或Curl方式测试接口,使用swagger简直就是傻瓜式操作,不需要额外说明文档(写得好本身就是文档)而且更不容易出错,只需要录入数据然后点击Execute,如果再配合自动化框架,可以说基本就不需要人为操作了。
Swagger是个优秀的工具,现在国内已经有很多的中小型互联网公司都在使用它,相较于传统的要先出Word接口文档再测试的方式,显然这样也更符合现在的快速迭代开发行情。当然了,提醒下大家在正式环境要记得关闭Swagger,一来出于安全考虑二来也可以节省运行时内存。
其他皮肤 我们可以导入不同的包实现不同的皮肤定义:
1、默认的 访问 http://localhost:8080/swagger-ui.html
1 2 3 4 5 <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger-ui</artifactId > <version > 2.9.2</version > </dependency >
2、bootstrap-ui 访问 http://localhost:8080/doc.html
1 2 3 4 5 6 <dependency > <groupId > com.github.xiaoymin</groupId > <artifactId > swagger-bootstrap-ui</artifactId > <version > 1.9.1</version > </dependency >
3、Layui-ui 访问 http://localhost:8080/docs.html
使用这个必须设置默认分组,否则会报错Unable to find specification for group default
1 2 3 4 5 6 <dependency > <groupId > com.github.caspar-chen</groupId > <artifactId > swagger-ui-layer</artifactId > <version > 1.1.3</version > </dependency >
4、mg-ui 访问 http://localhost:8080/document.html
1 2 3 4 5 6 <dependency > <groupId > com.zyplayer</groupId > <artifactId > swagger-mg-ui</artifactId > <version > 1.0.6</version > </dependency >
Swagger3 对比: 和swagger2对比:更好看的UI,修复了一些bug,
使用上的区别:
新版本和老版本的区别主要体现在以下 4 个方面:
1:依赖 项的添加不同:新版本只需要添加一项,而老版本需要添加两项;
2:启动 Swagger 的注解不同:新版本使用的是 @EnableOpenApi ,而老版本是 @EnableSwagger2;
3:Docket(文档摘要信息)的文件类型配置不同:新版本配置的是 OAS_3 ,而老版本是 SWAGGER_2;
1:Swagger 可以看作是一个遵循了 OpenAPI 规范的一项技术,而 springfox Swagger 则是这项技术的具体实现 2:OAS 是 OpenAPI Specification 的简称,翻译成中文就是 OpenAPI 说明书。
4:Swagger UI 访问地址不同:新版本访问地址是“**http://localhost:8080/swagger-ui/**”,而老版本访问地址是“http://localhost:8080/swagger-ui.html”
Ps:在使用swagger的时候,通常需要使用【@ApiParam】注解指定接口中参数的名字 ,特别是接口是post请求且参数使用了@RequestParam注解时
示例: 1:导入依赖
1 2 3 4 5 <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-boot-starter</artifactId > <version > 3.0.0</version > </dependency >
2:书写配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.oas.annotations.EnableOpenApi;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import java.util.ArrayList;@Configuration @EnableOpenApi public class SwaggerConfig { @Bean public Docket docket () { return new Docket (DocumentationType.OAS_30) .apiInfo(apiInfo()); } private ApiInfo apiInfo () { Contact contact = new Contact ("联系人名字" , "http://xxx.xxx.com/联系人访问链接" , "联系人邮箱" ); return new ApiInfo ( "Swagger学习" , "学习演示如何配置Swagger" , "v1.0" , "http://terms.service.url/组织链接" , contact, "Apach 2.0 许可" , "许可链接" , new ArrayList <>() ); } }
3:拦截器中排除swagger
4:访问:http://localhost:8080/swagger-ui/
Swagger3 常用配置注解
@Api
:用在请求的类上,表示对类的说明
tags=”说明该类的作用,可以在UI界面上看到的注解”
value=”该参数没什么意义,在UI界面上也看到,所以不需要配置”
@ApiOperation
:用在请求的方法上,说明方法的用途、作用
value=”说明方法的用途、作用”
notes=”方法的备注说明”
@ApiImplicitParams
:用在请求的方法上,表示一组参数说明
@ApiImplicitParam
:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header –> 请求参数的获取:@RequestHeader
· query –> 请求参数的获取:@RequestParam
· path(用于restful接口)–> 请求参数的获取:@PathVariable
· div(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType=”Integer”
defaultValue:参数的默认值
@ApiResponses
:用在请求的方法上,表示一组响应
@ApiResponse
:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如”请求参数没填好”
response:抛出异常的类
@ApiModel
:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景, 请求参数无法使用@ApiImplicitParam 注解进行描述的时候)
@ApiModelProperty
:用在属性上,描述响应类的属性
实例一 @ApiImplicitParams 和 @ApiImplicitParam 参数描述
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Api(tags = "测试") @RestController public class HelloController { @GetMapping("/hello") public String hello () { return "hello" ; } @PostMapping("/search") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "query"), @ApiImplicitParam(name = "age", value = "年龄", required = true, paramType = "query", dataType = "Integer") }) @ApiOperation("查找用户") public String search (String name, Integer age) { return name + ":" + age; } }
实例二 @ApiModel , @ApiModelProperty 实体参数描述
参考上述
实例三 @ApiResponses , @ApiResponse
我们搞一个根据id获取用户信息案例,通过 @PathVariable 获取id,返回User对象,以及通过@ApiResponses , @ApiResponse ,描述响应码对应的描述信息
1 2 3 4 5 6 7 8 9 10 11 12 13 @GetMapping("/user/{id}") @ApiOperation("根据ID获取用户信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户编号", required = true, paramType = "path") }) @ApiResponses({ @ApiResponse(code=400,message = "请求参数为空"), @ApiResponse(code=404,message = "请求路径为空"), @ApiResponse(code=444,message = "自定义错误信息"), }) public User load (@PathVariable("id") Integer id) { return new User (id, "mike" , 22 ); }
security