转载于:https://blog.csdn.net/sanyaoxu_2/article/details/80555328

1:认识Swagger

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

 作用:

    1. 接口的文档在线自动生成。

    2. 功能测试。

 Swagger是一组开源项目,其中主要要项目如下:

1.   Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。

2.   Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。

3.   Swagger-js: 用于JavaScript的Swagger实现。

4.   Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。

5.   Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。

6.   Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。

2:Maven

版本号请根据实际情况自行更改。

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.2.2</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.2.2</version>

</dependency>

3:创建Swagger2配置类

在Application.java同级创建Swagger2的配置类Swagger2

 
  1. package com.swaggerTest;

  2. import org.springframework.context.annotation.Bean;

  3. import org.springframework.context.annotation.Configuration;

  4. import springfox.documentation.builders.ApiInfoBuilder;

  5. import springfox.documentation.builders.PathSelectors;

  6. import springfox.documentation.builders.RequestHandlerSelectors;

  7. import springfox.documentation.service.ApiInfo;

  8. import springfox.documentation.spi.DocumentationType;

  9. import springfox.documentation.spring.web.plugins.Docket;

  10. import springfox.documentation.swagger2.annotations.EnableSwagger2;

  11. /**

  12. * Swagger2配置类

  13. * 在与spring boot集成时,放在与Application.java同级的目录下。

  14. * 通过@Configuration注解,让Spring来加载该类配置。

  15. * 再通过@EnableSwagger2注解来启用Swagger2。

  16. */

  17. @Configuration

  18. @EnableSwagger2

  19. public class Swagger2 {

  20. /**

  21. * 创建API应用

  22. * apiInfo() 增加API相关信息

  23. * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,

  24. * 本例采用指定扫描的包路径来定义指定要建立API的目录。

  25. *

  26. * @return

  27. */

  28. @Bean

  29. public Docket createRestApi() {

  30. return new Docket(DocumentationType.SWAGGER_2)

  31. .apiInfo(apiInfo())

  32. .select()

  33. .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))

  34. .paths(PathSelectors.any())

  35. .build();

  36. }

  37. /**

  38. * 创建该API的基本信息(这些基本信息会展现在文档页面中)

  39. * 访问地址:http://项目实际地址/swagger-ui.html

  40. * @return

  41. */

  42. private ApiInfo apiInfo() {

  43. return new ApiInfoBuilder()

  44. .title("Spring Boot中使用Swagger2构建RESTful APIs")

  45. .description("更多请关注http://www.baidu.com")

  46. .termsOfServiceUrl("http://www.baidu.com")

  47. .contact("sunf")

  48. .version("1.0")

  49. .build();

  50. }

  51. }

如上代码所示,通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。

4:添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函数的命名,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。

Swagger使用的注解及其说明:

@Api:用在类上,说明该类的作用。

@ApiOperation:注解来给API增加方法说明。

@ApiImplicitParams : 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

l   code:数字,例如400

l   message:信息,例如"请求参数没填好"

l   response:抛出异常的类

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

l   @ApiModelProperty:描述一个model的属性

注意:@ApiImplicitParam的参数说明:

paramType:指定参数放在哪个地方

header:请求参数放置于Request Header,使用@RequestHeader获取

query:请求参数放置于请求地址,使用@RequestParam获取

path:(用于restful接口)-->请求参数的获取:@PathVariable

body:(不常用)

form(不常用)

name:参数名

dataType:参数类型

required:参数是否必须传

true | false

value:说明参数的意思

defaultValue:参数的默认值

例子:

 
  1. package com.swaggerTest.controller;

  2. import org.springframework.stereotype.Controller;

  3. import org.springframework.util.StringUtils;

  4. import org.springframework.web.bind.annotation.RequestMapping;

  5. import org.springframework.web.bind.annotation.RequestMethod;

  6. import org.springframework.web.bind.annotation.RequestParam;

  7. import org.springframework.web.bind.annotation.ResponseBody;

  8. import io.swagger.annotations.Api;

  9. import io.swagger.annotations.ApiImplicitParam;

  10. import io.swagger.annotations.ApiImplicitParams;

  11. import io.swagger.annotations.ApiOperation;

  12. /**

  13. * 一个用来测试swagger注解的控制器

  14. * 注意@ApiImplicitParam的使用会影响程序运行,如果使用不当可能造成控制器收不到消息

  15. *

  16. * @author SUNF

  17. */

  18. @Controller

  19. @RequestMapping("/say")

  20. @Api(value = "SayController|一个用来测试swagger注解的控制器")

  21. public class SayController {

  22. @ResponseBody

  23. @RequestMapping(value ="/getUserName", method= RequestMethod.GET)

  24. @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回")

  25. @ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")

  26. public String getUserName(@RequestParam Integer userNumber){

  27. if(userNumber == 1){

  28. return "张三丰";

  29. }

  30. else if(userNumber == 2){

  31. return "慕容复";

  32. }

  33. else{

  34. return "未知";

  35. }

  36. }

  37. @ResponseBody

  38. @RequestMapping("/updatePassword")

  39. @ApiOperation(value="修改用户密码", notes="根据用户id修改密码")

  40. @ApiImplicitParams({

  41. @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),

  42. @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),

  43. @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")

  44. })

  45. public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password,

  46. @RequestParam(value="newPassword") String newPassword){

  47. if(userId <= 0 || userId > 2){

  48. return "未知的用户";

  49. }

  50. if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){

  51. return "密码不能为空";

  52. }

  53. if(password.equals(newPassword)){

  54. return "新旧密码不能相同";

  55. }

  56. return "密码修改成功!";

  57. }

  58. }

完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html

如上图,可以看到暴漏出来的控制器信息,点击进入可以看到详细信息。

两个注意点:

1.  paramType会直接影响程序的运行期,如果paramType与方法参数获取使用的注解不一致,会直接影响到参数的接收。

例如:

使用Sawgger UI进行测试,接收不到!

2.  还有一个需要注意的地方:

Conntroller中定义的方法必须在@RequestMapper中显示的指定RequestMethod类型,否则SawggerUi会默认为全类型皆可访问, API列表中会生成多条项目。

如上图:updatePassword()未指定requestMethod,结果生成了7条API信息。所以如果没有特殊需求,建议根据实际情况加上requestMethod。

5:Swagger UI面板说明

6:参考

http://blog.didispace.com/springbootswagger2/

http://blog.csdn.net/jia20003/article/details/50700736

Swagger官网 :http://swagger.io/

Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/

Github:https://github.com/swagger-api/swagger-core/wiki/Annotations

---------------------------------------------------------------------------------------

7:接收对象传参的例子

在POJO上增加

 
  1. package com.zhongying.api.model.base;

  2. import io.swagger.annotations.ApiModel;

  3. import io.swagger.annotations.ApiModelProperty;

  4. /**

  5. * 医生对象模型,不要使用该类

  6. * @author SUNF

  7. *

  8. */

  9. @ApiModel(value="医生对象模型")

  10. public class DemoDoctor{

  11. @ApiModelProperty(value="id" ,required=true)

  12. private Integer id;

  13. @ApiModelProperty(value="医生姓名" ,required=true)

  14. private String name;

  15. public Integer getId() {

  16. return id;

  17. }

  18. public void setId(Integer id) {

  19. this.id = id;

  20. }

  21. public String getName() {

  22. return name;

  23. }

  24. public void setName(String name) {

  25. this.name = name;

  26. }

  27. @Override

  28. public String toString() {

  29. return "DemoDoctor [id=" + id + ", name=" + name + "]";

  30. }

  31. }

注意: 在后台采用对象接收参数时,Swagger自带的工具采用的是JSON传参,    测试时需要在参数上加入@RequestBody,正常运行采用form或URL提交时候请删除。 

 
  1. package com.zhongying.api.controller.app;

  2. import java.util.ArrayList;

  3. import java.util.List;

  4. import javax.servlet.http.HttpServletRequest;

  5. import org.springframework.stereotype.Controller;

  6. import org.springframework.web.bind.annotation.RequestBody;

  7. import org.springframework.web.bind.annotation.RequestMapping;

  8. import org.springframework.web.bind.annotation.RequestMethod;

  9. import org.springframework.web.bind.annotation.RequestParam;

  10. import org.springframework.web.bind.annotation.ResponseBody;

  11. import com.github.pagehelper.PageInfo;

  12. import com.zhongying.api.exception.HttpStatus401Exception;

  13. import com.zhongying.api.model.base.DemoDoctor;

  14. import io.swagger.annotations.Api;

  15. import io.swagger.annotations.ApiImplicitParam;

  16. import io.swagger.annotations.ApiImplicitParams;

  17. import io.swagger.annotations.ApiOperation;

  18. /**

  19. * 医生类(模拟)

  20. * @author SUNF

  21. */

  22. @RequestMapping("/api/v1")

  23. @Controller

  24. @Api(value = "DoctorTestController-医生信息接口模拟")

  25. public class DoctorTestController {

  26. /**

  27. * 添加医生

  28. *

  29. * 在使用对象封装参数进行传参时,需要在该对象添加注解,将其注册到swagger中

  30. * @link com.zhongying.api.model.base.DemoDoctor

  31. *

  32. * 注意: 在后台采用对象接收参数时,Swagger自带的工具采用的是JSON传参,

  33. * 测试时需要在参数上加入@RequestBody,正常运行采用form或URL提交时候请删除。

  34. *

  35. * @param doctor 医生类对象

  36. * @return

  37. * @throws Exception

  38. */

  39. @ResponseBody

  40. @RequestMapping(value="/doctor", method= RequestMethod.POST )

  41. @ApiOperation(value="添加医生信息", notes="")

  42. public String addDoctor(@RequestBody DemoDoctor doctor) throws Exception{

  43. if(null == doctor || doctor.getId() == null){

  44. throw new HttpStatus401Exception("添加医生失败","DT3388","未知原因","请联系管理员");

  45. }

  46. try {

  47. System.out.println("成功----------->"+doctor.getName());

  48. } catch (Exception e) {

  49. throw new HttpStatus401Exception("添加医生失败","DT3388","未知原因","请联系管理员");

  50. }

  51. return doctor.getId().toString();

  52. }

  53. /**

  54. * 删除医生

  55. * @param doctorId 医生ID

  56. * @return

  57. */

  58. @ResponseBody

  59. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.DELETE )

  60. @ApiOperation(value="删除医生信息", notes="")

  61. @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer")

  62. public String deleteDoctor(@RequestParam Integer doctorId){

  63. if(doctorId > 2){

  64. return "删除失败";

  65. }

  66. return "删除成功";

  67. }

  68. /**

  69. * 修改医生信息

  70. * @param doctorId 医生ID

  71. * @param doctor 医生信息

  72. * @return

  73. * @throws HttpStatus401Exception

  74. */

  75. @ResponseBody

  76. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.POST )

  77. @ApiOperation(value="修改医生信息", notes="")

  78. @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer")

  79. public String updateDoctor(@RequestParam Integer doctorId, @RequestBody DemoDoctor doctor) throws HttpStatus401Exception{

  80. if(null == doctorId || null == doctor){

  81. throw new HttpStatus401Exception("修改医生信息失败","DT3391","id不能为空","请修改");

  82. }

  83. if(doctorId > 5 ){

  84. throw new HttpStatus401Exception("医生不存在","DT3392","错误的ID","请更换ID");

  85. }

  86. System.out.println(doctorId);

  87. System.out.println(doctor);

  88. return "修改成功";

  89. }

  90. /**

  91. * 获取医生详细信息

  92. * @param doctorId 医生ID

  93. * @return

  94. * @throws HttpStatus401Exception

  95. */

  96. @ResponseBody

  97. @RequestMapping(value="/doctor/{doctorId}", method= RequestMethod.GET )

  98. @ApiOperation(value="获取医生详细信息", notes="仅返回姓名..")

  99. @ApiImplicitParam(paramType="query", name = "doctorId", value = "医生ID", required = true, dataType = "Integer")

  100. public DemoDoctor getDoctorDetail(@RequestParam Integer doctorId) throws HttpStatus401Exception{

  101. System.out.println(doctorId);

  102. if(null == doctorId){

  103. throw new HttpStatus401Exception("查看医生信息失败","DT3390","未知原因","请联系管理员");

  104. }

  105. if(doctorId > 3){

  106. throw new HttpStatus401Exception("医生不存在","DT3392","错误的ID","请更换ID");

  107. }

  108. DemoDoctor doctor = new DemoDoctor();

  109. doctor.setId(1);

  110. doctor.setName("测试员");

  111. return doctor;

  112. }

  113. /**

  114. * 获取医生列表

  115. * @param pageIndex 当前页数

  116. * @param pageSize 每页记录数

  117. * @param request

  118. * @return

  119. * @throws HttpStatus401Exception

  120. */

  121. @ResponseBody

  122. @RequestMapping(value="/doctor", method= RequestMethod.GET )

  123. @ApiOperation(value="获取医生列表", notes="目前一次全部取,不分页")

  124. @ApiImplicitParams({

  125. @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),

  126. @ApiImplicitParam(paramType="query", name = "pageIndex", value = "当前页数", required = false, dataType = "String"),

  127. @ApiImplicitParam(paramType="query", name = "pageSize", value = "每页记录数", required = true, dataType = "String"),

  128. })

  129. public PageInfo<DemoDoctor> getDoctorList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,

  130. @RequestParam(value = "pageSize", required = false) Integer pageSize,

  131. HttpServletRequest request) throws HttpStatus401Exception{

  132. String token = request.getHeader("token");

  133. if(null == token){

  134. throw new HttpStatus401Exception("没有权限","SS8888","没有权限","请查看操作文档");

  135. }

  136. if(null == pageSize){

  137. throw new HttpStatus401Exception("每页记录数不粗安在","DT3399","不存在pageSize","请查看操作文档");

  138. }

  139. DemoDoctor doctor1 = new DemoDoctor();

  140. doctor1.setId(1);

  141. doctor1.setName("测试员1");

  142. DemoDoctor doctor2 = new DemoDoctor();

  143. doctor2.setId(2);

  144. doctor2.setName("测试员2");

  145. List<DemoDoctor> doctorList = new ArrayList<DemoDoctor>();

  146. doctorList.add(doctor1);

  147. doctorList.add(doctor2);

  148. return new PageInfo<DemoDoctor>(doctorList);

  149. }

  150. }

增加header:

现在很多请求需要在header增加额外参数,可以参考getDoctorList()的做法,使用request接收。

Swagger2使用指南相关推荐

  1. Swagger2.0和resful规范

    文章目录 前言 一.swagger2.0,resful,openApi3.0是什么? 二.restful协议的内容 1.restful 2.reful协议的误区 就是URI包含动词:因为"资 ...

  2. SpringBoot2.1.6与Swagger2.9.2整合及前台输入框报错原因

    swagger2具体介绍请参考:Swagger使用指南 这里主要说明在使用Swagger高版本的时候,会遇到的一种错误: 在我测试如下第一个接口时: 展开第一个接口,点击Try it out! 后台我 ...

  3. 导出swagger2生成的文档

    百度了好多篇用法,没法用.特此记录一下 一.下载项目 下载https://github.com/Swagger2Markup/spring-swagger2markup-demo下的项目,保存,注意文 ...

  4. 超详细中文预训练模型ERNIE使用指南-源码

    作者 | 高开远,上海交通大学,自然语言处理研究方向 最近在工作上处理的都是中文语料,也尝试了一些最近放出来的预训练模型(ERNIE,BERT-CHINESE,WWM-BERT-CHINESE),比对 ...

  5. 入门指南目录页 -PaddlePaddle 飞桨 入门指南 FAQ合集-深度学习问题

    入门指南目录页 -PaddlePaddle 飞桨 入门指南 FAQ合集 GT_Zhang关注 0.1012019.08.01 18:43:34字数 1,874阅读 795 Hi,欢迎各位来自Paddl ...

  6. ASIC设计-终极指南

    ASIC设计-终极指南 ASIC Design – The Ultimate Guide ASIC设计-终极指南 ASICs代表特定于应用的集成电路,指的是针对特定应用而设计的半导体解决方案,与其他解 ...

  7. Python神经网络集成技术Guide指南

    Python神经网络集成技术Guide指南 本指南将介绍如何加载一个神经网络集成系统并从Python运行推断. 提示 所有框架的神经网络集成系统运行时接口都是相同的,因此本指南适用于所有受支持框架(包 ...

  8. 深度学习框架集成平台C++ Guide指南

    深度学习框架集成平台C++ Guide指南 这个指南详细地介绍了神经网络C++的API,并介绍了许多不同的方法来处理模型. 提示 所有框架运行时接口都是相同的,因此本指南适用于所有受支持框架(包括Te ...

  9. HTML5与CSS3权威指南之CSS3学习记录

    title: HTML5与CSS3权威指南之CSS3学习记录 toc: true date: 2018-10-14 00:06:09 学习资料--<HTML5与CSS3权威指南>(第3版) ...

最新文章

  1. Active Directory操作主机详解
  2. java数组可扩展_[转载]Java数组扩容算法及Java对它的应用
  3. 开放下载!《ECS运维指南 之 windows系统诊断》
  4. 面试官:缓存一致性问题怎么解决?
  5. 毛毛虫组【Beta】Scrum Meeting 3
  6. 使用QXDM Log 來分析LTE環境資訊
  7. CSS系列教程----摘自洪恩网站
  8. java语言程序设计二级_计算机二级Java语言程序设计试题
  9. ROM RAM FLASH说明
  10. java利用TOTP算法动态生成一次性密码
  11. 女性贫血的经典食疗方
  12. DS1302时钟(进阶版)可调日期和时间等
  13. Spring-Boot Dubbo 整合
  14. MethodHandle.invoke and MethodHandle.invokeExact are only supported starting with Android O
  15. windows下使用Redis6
  16. IDEA插件系列(64):Document Assistant插件——SpringMVC文档助手
  17. java输入名字和语句_java键盘输入语句怎么写
  18. 百度地图开发系列(5):高亮显示省市县级别的行政区域
  19. 4399大数据笔试题
  20. 计算机应用基础000,计算机应用基础题型.doc

热门文章

  1. win10应用商店edge等无法联网 错误代码为 0x8000FFFF
  2. 回首2021,剑指 2022 | 一个00后程序员的华丽蜕变
  3. ixp425开发板下移植hostapd做虚拟ap环境
  4. functions.php 在哪,【WordPress 如何在当前主题的 functions.php 里添加代码】-wordpress教程-【零度中国】...
  5. c语言scanf错误c4996,C语言常见错误杂谈(一)scanf()、scanf_s()与错误 C4996与解决方法...
  6. python定义向量_python中向量怎么表示
  7. 饿了吗数据采集的10个经典方法
  8. swiftUI-官方文档(to be continued)
  9. numpy.quantile
  10. PHP全栈学习笔记16