一切参数说明,参考官方API文档:http://docs.swagger.io/swagger-core/current/apidocs/index.html?io/swagger/annotations

在实体和API注释这块,有些注释不一定在页面上表现,但是接口返回的数据上全部都有返回。

Swagger2出自SpringFOX, 官网:https://github.com/springfox/springfox,而与https://swagger.io/不同,所以在https://swagger.io/上是找不到Swagger2的开发文档。

在Swagger2的GitHUb页面上也没提供相关的详细文档,不过可以参考示例代码库https://github.com/springfox/springfox-demos进行参考。

不过下面这些网址还能找到关于Swagger的先关API文档,并且兼容Swagger2的:

http://docs.swagger.io/swagger-core/current/apidocs/index.html

https://github.com/swagger-api/swagger-core(旧版示例)

https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

https://github.com/swagger-api/swagger-samples(新版示例)

下面是收集的一些常用注解,如果要更多的用法,可以参照上面官网提供的文档:

名称 描述
@Api 将类标记为Swagger资源。
@ApiImplicitParam 表示API操作中的单个参数。
@ApiImplicitParams 允许多个ApiImplicitParam对象列表的包装器。
@ApiModel 提供有关Swagger型号的其他信息。
@ApiModelProperty 添加和操作模型属性的数据。
@ApiOperation 描述针对特定路径的操作或通常的HTTP方法。
@ApiParam 为操作参数添加额外的元数据。
@ApiResponse 描述操作的可能响应。
@ApiResponses 允许多个ApiResponse对象列表的包装器。
@Authorization 声明在资源或操作上使用授权方案。
@AuthorizationScope 描述OAuth2授权范围。
@ResponseHeader 表示可以作为响应的一部分提供的头。

示例代码:

SwaggerConfig 配置

  1. import com.google.common.base.Predicate;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.http.ResponseEntity;
  6. import springfox.documentation.service.ApiInfo;
  7. import springfox.documentation.spi.DocumentationType;
  8. import springfox.documentation.spring.web.plugins.Docket;
  9. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  10.  
  11. import static com.google.common.base.Predicates.or;
  12. import static springfox.documentation.builders.PathSelectors.regex;
  13.  
  14. /**
  15. * SwaggerConfig
  16. */
  17. @Configuration
  18. @EnableSwagger2
  19. public class SwaggerConfig {
  20.  
  21. @Value("${server.servlet-path}")
  22. private String pathMapping;
  23.  
  24. private ApiInfo initApiInfo() {
  25. ApiInfo apiInfo = new ApiInfo("XXX项目 Platform API",//大标题
  26. initContextInfo(),//简单的描述
  27. "1.0.0",//版本
  28. "服务条款",
  29. "后台开发团队",//作者
  30. "The Apache License, Version 2.0",//链接显示文字
  31. "http://www.baidu.com"//网站链接
  32. );
  33.  
  34. return apiInfo;
  35. }
  36.  
  37. private String initContextInfo() {
  38. StringBuffer sb = new StringBuffer();
  39. sb.append("REST API 设计在细节上有很多自己独特的需要注意的技巧,并且对开发人员在构架设计能力上比传统 API 有着更高的要求。")
  40. .append("<br/>")
  41. .append("本文通过翔实的叙述和一系列的范例,从整体结构,到局部细节,分析和解读了为了提高易用性和高效性,REST API 设计应该注意哪些问题以及如何解决这些问题。");
  42.  
  43. return sb.toString();
  44. }
  45.  
  46. @Bean
  47. public Docket restfulApi() {
  48. System.out.println("http://localhost:8080" + pathMapping + "/swagger-ui.html");
  49.  
  50. return new Docket(DocumentationType.SWAGGER_2)
  51. .groupName("RestfulApi")
  52. // .genericModelSubstitutes(DeferredResult.class)
  53. .genericModelSubstitutes(ResponseEntity.class)
  54. .useDefaultResponseMessages(true)
  55. .forCodeGeneration(false)
  56. .pathMapping(pathMapping) // base,最终调用接口后会和paths拼接在一起
  57. .select()
  58. .paths(doFilteringRules())
  59. .build()
  60. .apiInfo(initApiInfo());
  61. }
  62.  
  63. /**
  64. * 设置过滤规则
  65. * 这里的过滤规则支持正则匹配
  66. * @return
  67. */
  68. private Predicate<String> doFilteringRules() {
  69. return or(
  70. regex("/hello.*"),
  71. regex("/vehicles.*")
  72. );
  73. }
  74. }

Controller 的配置

  1. import com.reachauto.hkr.cxn.swagger.bean.ChangeRentalShopParameter;
  2. import io.swagger.annotations.*;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.ui.ModelMap;
  6. import org.springframework.web.bind.annotation.*;
  7.  
  8. import java.util.Date;
  9.  
  10. @Api(value = "API - VehiclesController", description = "车辆模块接口详情")
  11. @RestController
  12. @RequestMapping("/vehicles")
  13. public class VehiclesController {
  14.  
  15. private static Logger logger = LoggerFactory.getLogger(VehiclesController.class);
  16.  
  17. @ApiOperation(value = "查询车辆接口", notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得庆幸的是这儿支持html标签<hr/>", response = String.class)
  18. @ApiImplicitParams({
  19. @ApiImplicitParam(name = "vno", value = "车牌", required = false,
  20. dataType = "string", paramType = "query", defaultValue = "辽A12345"),
  21. @ApiImplicitParam(name = "page", value = "page", required = false,
  22. dataType = "Integer", paramType = "query",defaultValue = "1"),
  23. @ApiImplicitParam(name = "count", value = "count", required = false,
  24. dataType = "Integer", paramType = "query",defaultValue = "10")
  25. })
  26. @ApiResponses(value = {
  27. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  28. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  29. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  30. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  31. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  32. )
  33. @ResponseBody
  34. @RequestMapping(value = "", method = RequestMethod.GET)
  35. public ModelMap findVehicles(@RequestParam(value = "vno", required = false) String vno,
  36. @RequestParam(value = "page", required = false) Integer page,
  37. @RequestParam(value = "count", required = false) Integer count)
  38. throws Exception {
  39.  
  40. logger.info("http://localhost:8501/api/v1/vehicles");
  41. logger.info("## {},{},{}", vno, page, count);
  42. logger.info("## 请求时间:{}", new Date());
  43.  
  44. ModelMap map = new ModelMap();
  45. map.addAttribute("vno", vno);
  46. map.addAttribute("page", page);
  47. return map;
  48. }
  49.  
  50. @ApiOperation(value = "根据车牌查询车辆", notes = "这种类型的查询是精确查询,其结果只有一条数据", response = String.class)
  51. @ApiImplicitParams({
  52. @ApiImplicitParam(name = "vno", value = "车牌", required = false,
  53. dataType = "string", paramType = "path", defaultValue = "辽A12345")
  54. })
  55. @ApiResponses(value = {
  56. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  57. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  58. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  59. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  60. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  61. )
  62. @ResponseBody
  63. @RequestMapping(value = "vno={vno}", method = RequestMethod.GET)
  64. public ModelMap getVno(@PathVariable(value = "vno") String vno)
  65. throws Exception {
  66.  
  67. logger.info("http://localhost:8501/api/v1/vehicles/vno={}", vno);
  68. logger.info("## 请求时间:{}", new Date());
  69.  
  70. ModelMap map = new ModelMap();
  71. map.addAttribute("vno", vno);
  72.  
  73. return map;
  74. }
  75.  
  76. @ApiOperation(value = "车辆位置查询接口", notes = "根据车牌查询车辆位置信息", response = String.class)
  77. @ApiImplicitParams({
  78. @ApiImplicitParam(name = "vno", value = "车牌", required = false,
  79. dataType = "string", paramType = "path", defaultValue = "辽A12345")
  80. })
  81. @ApiResponses(value = {
  82. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  83. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  84. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  85. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  86. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  87. )
  88. @ResponseBody
  89. @RequestMapping(value = "vno={vno}/location", method = RequestMethod.GET)
  90. public ModelMap getLocation(@PathVariable(value = "vno") String vno)
  91. throws Exception {
  92. logger.info("getLocation");
  93. logger.info("## 请求时间:{}", new Date());
  94.  
  95. ModelMap map = new ModelMap();
  96. map.addAttribute("vno", vno);
  97.  
  98. return map;
  99. }
  100.  
  101. @ApiOperation(value = "根据车辆id查询", notes = "精确查询,最常规的方式,支持POST和GET方式", response = String.class)
  102. @ApiImplicitParams({
  103. @ApiImplicitParam(name = "id", value = "id", required = false,
  104. dataType = "string", paramType = "path", defaultValue = "12344444")
  105. })
  106. @ApiResponses(value = {
  107. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  108. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  109. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  110. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  111. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  112. )
  113. @ResponseBody
  114. @RequestMapping(value = "{id}", method = {RequestMethod.GET,RequestMethod.POST})
  115. public ModelMap getById(@PathVariable(value = "id") String id)
  116. throws Exception {
  117.  
  118. logger.info("http://localhost:8501/api/v1/vehicles/{}", id);
  119. logger.info("## 请求时间:{}", new Date());
  120.  
  121. ModelMap map = new ModelMap();
  122. map.addAttribute("{RequestMethod.GET,RequestMethod.POST}", id);
  123.  
  124. return map;
  125. }
  126. @ApiOperation(value = "根据车辆id查询", notes = "精确查询,最常规的方式,支持POST和GET方式", response = String.class)
  127. @ApiImplicitParams({
  128. @ApiImplicitParam(name = "id", value = "id", required = false,
  129. dataType = "string", paramType = "path", defaultValue = "12344444")
  130. })
  131. @ApiResponses(value = {
  132. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  133. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  134. @ApiResponse(code = 403, message = "服务器拒绝请求"),
  135. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  136. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  137. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  138. )
  139. @ResponseBody
  140. @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
  141. public ModelMap delById(@PathVariable(value = "id") String id)
  142. throws Exception {
  143.  
  144. logger.info("http://localhost:8501/api/v1/vehicles/{}", id);
  145. logger.info("## 请求时间:{}", new Date());
  146.  
  147. ModelMap map = new ModelMap();
  148. map.addAttribute("RequestMethod.DELETE", id);
  149. return map;
  150. }
  151.  
  152. @ApiOperation(value = "网点挂靠", notes = "嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻", response = String.class)
  153. @ApiResponses(value = {
  154. @ApiResponse(code = 200, message = "Successful — 请求已完成"),
  155. @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
  156. @ApiResponse(code = 401, message = "未授权客户机访问数据"),
  157. @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
  158. @ApiResponse(code = 500, message = "服务器不能完成请求")}
  159. )
  160. @ResponseBody
  161. @RequestMapping(value = "change_rentalshop", method = {RequestMethod.PUT,RequestMethod.PATCH})
  162. public ModelMap changeRentalShop(@RequestBody ChangeRentalShopParameter parameter)
  163. throws Exception {
  164.  
  165. logger.info("http://localhost:8501/api/v1/vehicles/change_rentalshop | {}", parameter);
  166. logger.info("## 请求时间:{}", new Date());
  167. ModelMap map = new ModelMap();
  168. map.addAttribute("网点挂靠", new Date());
  169.  
  170. return map;
  171. }
  172. }

Application 启动模块

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5.  
  6. @Configuration
  7. @EnableAutoConfiguration
  8. @ComponentScan
  9. public class Application {
  10. public static void main(String[] args) {
  11. SpringApplication.run(Application.class, args);
  12. }
  13. }

示例代码输出的效果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/swagger2test/test1

参考:

https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/

https://gumutianqi1.gitbooks.io/specification-doc/content/tools-doc/spring-boot-swagger2-guide.html(以上内容部分转自此篇文章)

http://blog.csdn.net/xupeng874395012/article/details/68946676

http://blog.csdn.net/z28126308/article/details/71126677

http://blog.csdn.net/u014231523/article/details/76522486

http://blog.csdn.net/fanpeng1100/article/details/54016292

SpringFox Swagger2注解基本用法的更多相关文章

  1. SpringBoot中使用springfox+swagger2书写API文档

    随着前后端的分离,借口文档变的尤其重要,springfox是通过注解的形式自动生成API文档,利用它,可以很方便的书写restful API,swagger主要用于展示springfox生成的API文 ...

  2. 使用springfox+swagger2书写API文档(十八)

    使用springfox+swagger2书写API文档 springfox是通过注解的形式自动生成API文档,利用它,可以很方便的书写restful API,swagger主要用于展示springfo ...

  3. 浅谈@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别

    浅谈@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别 Spring 2.5 版本新增了注解功能, 通过注解,代码编写简化了很多:但熟悉注解的使 ...

  4. MP实战系列(十)之SpringMVC集成SpringFox+Swagger2

    该示例基于之前的实战系列,如果公司框架是使用JDK7以上及其Spring+MyBatis+SpringMVC/Spring+MyBatis Plus+SpringMVC可直接参考该实例. 不过建议最好 ...

  5. springboot swagger2注解使用

    swagger2 注解整体说明 @Api:用在请求的类上,表示对类的说明 tags="说明该类的作用,可以在UI界面上看到的注解" value="该参数没什么意义,在UI ...

  6. Spring的注解@Qualifier用法

    Spring的注解@Qualifier用法在Controller中需要注入service那么我的这个server有两个实现类如何区分开这两个impl呢?根据注入资源的注解不同实现的方式有一点小小的区别 ...

  7. 全面解析Spring中@ModelAttribute注解的用法

    本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:全面解析Spring中@ModelAttribute注解的用法: @ModelAttribute注解用于将方法的参数或方法的返回值绑定到 ...

  8. Hibernate 注解的用法以及说明(二)

    注解映射必须满足两大条件:Hibernate3.2以上版本和JSEE 5. @Entity 类注释,所有要持久化的类都要有@Entity   public class Org  implements ...

  9. spring的@Transactional注解详细用法

    概述 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性.Spring Framework对事务管理提供了一致的抽象,其特点如下: 为不同的事务API提供一致的编程模型, ...

随机推荐

  1. cocos creator 场景如何透明,多个canvas层级显示

    转载地址:https://forum.cocos.com/t/creator-canvas/55373/14 Creator 版本:1.7 目标平台:WEB MOBILE 项目需要,页面做了多个Can ...

  2. js易混API汇总

    一:slice()方法 ————————————http://www.w3school.com.cn/jsref/jsref_slice_string.asp ———————————————————— ...

  3. Java 8 (8) 默认方法

    传统上,Java程序的接口是将相关方法按照预定组合到一起的方式.实现接口的类必须为接口中定义的方法提供一个实现,或者从父类中集成它的实现.但是,一旦类库的设计者需要更新接口,向接口中加入新的方法时候, ...

  4. LN : leetcode 406 Queue Reconstruction by Height

    lc 406 Queue Reconstruction by Height 406 Queue Reconstruction by Height Suppose you have a random l ...

  5. es6数值扩展

    1. 二进制和八进制表示法 从 ES5 开始,在严格模式之中,八进制就不再允许使用前缀0表示,ES6 进一步明确,要使用前缀0o表示. ES6 提供了二进制和八进制数值的新的写法,分别用前缀0b(或0 ...

  6. android调用webservice接口获取信息

    我的有一篇博客上讲了如何基于CXF搭建webservice,service层的接口会被部署到tomcat上,这一篇我就讲一下如何在安卓中调用这些接口传递参数. 1.在lib中放入ksoap2的jar包 ...

  7. px-em-rem单位转换

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  8. mysql 存储引擎学习

    现在我们常用的MySQL存储引擎主要是两种:InnoDB and MyISAM. 1.MyISAM 执行效率高 不支持事务 不支持外键 每个MyISAM在磁盘上存储成3个文件,其中文件名和表名都相同, ...

  9. JAVA环境变量配置后未变动配置失效处理

    环境: Windows 7 x64 配置方案来源于教程: http://www.mamicode.com/info-detail-563355.html 配置方案出现的问题: 正确配置JAVA环境变量 ...

  10. Java学习2_一些基础2_字符串_16.5.5

    接上一次的博客. 不可变字符串: Java中String类没有提供用于修改字符串的方法.如果想将greeting中的“Hello”改为“Help!”需要先提取所需要的的字符,然后再拼接.即 greet ...