当前位置:   article > 正文

前言技术之swagger_swagger 注释的好处

swagger 注释的好处

一.前后端分离的特点

前后端分离是的前端与后端之间的职责更加明确

后台: 负责业务处理

前端: 负责显示逻辑

在这种情况下,前端和后端可以分别交付给专业的开发人员去做,所以是必须要定义前后端直接的对接

接口,否则各自为是则项目无法集成,这时就需要一个文档来定义统一的接口。

二.在没有swagger之前

在没有swagger之间,我们可以使用word,excel等功能来书写接口定义文档,但又有一个弊端,即:

在接口发送改变时需要及时的同步接口文档,否则实际的接口与接口文档不相符,则接口文件就失去了

作用,甚至会起到反作用。

三.swagger的作用

根据在代码中使用自定义的注解来生成接口文档,这个在前后端分离的项目中很重要。这样做的好处是

在开发接口时可以通过swagger将接口文档定义好,同时也方便以后的维护。

四.swagger的优点

号称时最流行的API框架

接口文档在线生成,避免同步的麻烦

可以支持在线对接口执行测试

支持多语言

五.集成swagger

5.1 新建springboot项目

使用集成开发工具创建一个springboot工程

5.2 集成swagger

1.pom.xml

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>swagger</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.编写swagger配置类

  1. package com.ycx.swagger.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import springfox.documentation.builders.ApiInfoBuilder;
  6. import springfox.documentation.builders.PathSelectors;
  7. import springfox.documentation.builders.RequestHandlerSelectors;
  8. import springfox.documentation.service.ApiInfo;
  9. import springfox.documentation.spi.DocumentationType;
  10. import springfox.documentation.spring.web.plugins.Docket;
  11. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  12. @Configuration
  13. @EnableSwagger2
  14. public class SwaggerConfig {
  15. @Bean
  16. public Docket createRestApi(){
  17. return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
  18. .select()
  19. .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
  20. .paths(PathSelectors.ant("/**")) //项目名
  21. .build();
  22. }
  23. private ApiInfo apiInfo() {
  24. return new ApiInfoBuilder()
  25. .title("SwaggerDemoAPIDOC")
  26. .description("SwaggerDemoAPIDOC")
  27. .version("1.0")
  28. .termsOfServiceUrl("https://www.baidu.com").build();
  29. }
  30. }

注意:SpringBoot与swagger2的版本对应关系,否则项目是启动不成功的,这里的版本对应关系如下

5.3 开发一个controller用于测试

  1. package com.ycx.swagger.web;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiOperation;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. //@Api(tags = {"这是swagger入门类","作用2"})
  11. @Api(tags = "这是swagger入门类")
  12. @RestController
  13. @RequestMapping("/swagger")
  14. public class HelloController {
  15. // @ApiOperation(value = "", tags = "swagger入门方法")
  16. @ApiOperation(value = "swagger入门方法")
  17. @GetMapping("/hello")
  18. public Map<String,Object> hello(){
  19. Map<String,Object> map = new HashMap<>();
  20. map.put("code",200);
  21. map.put("msg","响应成功!!!");
  22. return map;
  23. }
  24. }

5.4 启动服务,验证集成效果

服务启动后,访问:http://localhost:8080/swagger-ui.html

说明集成成功

6.swagger常用注解


注解

位置

作用

参数

@Api

标识这个类是swagger的资源

tags:说明该类的作用,参数是个数组,可 以填多个。

value="该参数没什么意义,在UI界面上不显示,所以不用配置"

description = "用户基本信息操作"

@ApiOperation

方法

表示一个http请求的操作

value="方法的用途和作用"

notes="方法的注意事项和备注"

tags:说明该方法的作用,参数是个数组,可以填多 个。

格式:tags={"作用1","作用2"}

@ApiParam

方法,参数

对参数使用说明(如:说明 或是否必填等)

value="用户名" 描述参数的意义

name="name" 参数的变量名

required=true 参数是否必选

@ApiModel

表示对类进行说明,用于参 数用实体类接收,一般用在 DTO上

description="描述实体的作用"

@ApiModelProperty

方法,字段

表示对model属性的说明

value="用户名" 描述参 数的意义

name="name" 参数的变量名

required=true 参数是否必选

@ApiIgnore

类,方法,参数

表示这个方法或者类被忽略

@ApiImplicitParams

方法

包含多@ApiImplicitParam

@ApiImplicitParam

方法

表示单独的请求参数

name="参数名称"

value="参数说明"

dataType="数据类型"

paramType="query" 表示参数放在哪里

defaultValue="参数的默认值"

required="true" 表示参数是否必须传

paramType="query"的解释如下

header 请求参数的获取:@RequestHeader

query 请求参数的获取:@RequestParam

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

body(不常用)

form(不常用)

更全面的信息可以参考官方说明文档:

https://docs.swagger.io/swagger-core/apidocs/index.html

    • swagger使用综合案例

  1. package com.ycx.swagger.web;
  2. import com.ycx.swagger.dto.User;
  3. import io.swagger.annotations.*;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. @RestController
  8. @RequestMapping("/swagger/api")
  9. @Api(tags = "swagger所有注解的讲解")
  10. public class SwaggerController {
  11. @ApiOperation(value = "欢迎信息")
  12. @GetMapping("/hello")
  13. @ApiImplicitParams({
  14. @ApiImplicitParam(name = "name", value = "名称", dataType = "string", paramType = "query", required = true),
  15. @ApiImplicitParam(name = "msg", value="消息", dataType = "string", paramType = "query", required = true)
  16. })
  17. public Object hello(String name, String msg) {
  18. Map<String, Object> map = new HashMap<>();
  19. map.put("code", 200);
  20. map.put("msg", "操作成功");
  21. map.put("info",name+":"+msg);
  22. return map;
  23. }
  24. @PostMapping("/register")
  25. @ApiOperation("注册用户接口")
  26. @ApiResponses({
  27. @ApiResponse(code = 5001001,message = "错误1"),
  28. @ApiResponse(code = 5001002,message = "错误2"),
  29. @ApiResponse(code = 5001003,message = "错误3")
  30. })
  31. public Object register(User user) {
  32. Map<String, Object> map = new HashMap<>();
  33. map.put("code", 5001002);
  34. map.put("msg", "操作成功");
  35. map.put("info",user);
  36. return map;
  37. }
  38. @PutMapping("/edit")
  39. @ApiOperation("修改用户信息")
  40. public Object edit(@RequestBody User user) {
  41. Map<String, Object> map = new HashMap<>();
  42. map.put("code", 200);
  43. map.put("msg", "操作成功");
  44. map.put("info",user);
  45. return map;
  46. }
  47. @DeleteMapping("/delete/{id}")
  48. @ApiOperation("删除用户")
  49. @ApiImplicitParam(name = "id", value="用户ID", dataType = "string", paramType = "path", required = true)
  50. public Object delete(@PathVariable("id") String id) {
  51. Map<String, Object> map = new HashMap<>();
  52. map.put("code", 200);
  53. map.put("msg", "操作成功");
  54. map.put("info",id);
  55. return map;
  56. }
  57. }

  1. package com.ycx.swagger.dto;
  2. import io.swagger.annotations.ApiModel;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.Data;
  5. @Data
  6. @ApiModel(description = "用户信息")
  7. public class User {
  8. @ApiModelProperty(value = "用户名", name="name", required = true)
  9. private String name;
  10. @ApiModelProperty(value = "密码", name="passwd", required = true)
  11. private String passwd;
  12. }

    • 会议OA之swagger

  1. pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.7.7</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ycx</groupId>
  12. <artifactId>minoa</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>minoa</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <fastjson.version>1.2.70</fastjson.version>
  19. <jackson.version>2.9.8</jackson.version>
  20. </properties>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-jdbc</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.mybatis.spring.boot</groupId>
  32. <artifactId>mybatis-spring-boot-starter</artifactId>
  33. <version>2.2.1</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>mysql</groupId>
  37. <artifactId>mysql-connector-java</artifactId>
  38. <version>5.1.44</version>
  39. <scope>runtime</scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <optional>true</optional>
  45. </dependency>
  46. <dependency>
  47. <groupId>com.alibaba</groupId>
  48. <artifactId>fastjson</artifactId>
  49. <version>${fastjson.version}</version>
  50. </dependency>
  51. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
  52. <dependency>
  53. <groupId>io.springfox</groupId>
  54. <artifactId>springfox-swagger2</artifactId>
  55. <version>2.9.2</version>
  56. </dependency>
  57. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
  58. <dependency>
  59. <groupId>io.springfox</groupId>
  60. <artifactId>springfox-swagger-ui</artifactId>
  61. <version>2.9.2</version>
  62. </dependency>
  63. </dependencies>
  64. <build>
  65. <plugins>
  66. <plugin>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-maven-plugin</artifactId>
  69. <configuration>
  70. <excludes>
  71. <exclude>
  72. <groupId>org.projectlombok</groupId>
  73. <artifactId>lombok</artifactId>
  74. </exclude>
  75. </excludes>
  76. </configuration>
  77. </plugin>
  78. <plugin>
  79. <groupId>org.mybatis.generator</groupId>
  80. <artifactId>mybatis-generator-maven-plugin</artifactId>
  81. <version>1.3.2</version>
  82. <dependencies>
  83. <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
  84. <dependency>
  85. <groupId>mysql</groupId>
  86. <artifactId>mysql-connector-java</artifactId>
  87. <version>${mysql.version}</version>
  88. </dependency>
  89. </dependencies>
  90. <configuration>
  91. <overwrite>true</overwrite>
  92. </configuration>
  93. </plugin>
  94. </plugins>
  95. </build>
  96. </project>

2.swagger的整合配置类

  1. package com.ycx.minoa.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import springfox.documentation.builders.ApiInfoBuilder;
  6. import springfox.documentation.builders.PathSelectors;
  7. import springfox.documentation.builders.RequestHandlerSelectors;
  8. import springfox.documentation.service.ApiInfo;
  9. import springfox.documentation.spi.DocumentationType;
  10. import springfox.documentation.spring.web.plugins.Docket;
  11. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  12. @Configuration
  13. @EnableSwagger2
  14. public class SwaggerConfig {
  15. @Bean
  16. public Docket createRestApi(){
  17. return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
  18. .select()
  19. .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
  20. .paths(PathSelectors.ant("/**")) //项目名
  21. .build();
  22. }
  23. private ApiInfo apiInfo() {
  24. return new ApiInfoBuilder()
  25. .title("SwaggerDemoAPIDOC")
  26. .description("SwaggerDemoAPIDOC")
  27. .version("1.0")
  28. .termsOfServiceUrl("https://www.baidu.com").build();
  29. }
  30. }

注意:此时SpringBoot (2.7.7) 版本与swagger2 (2.9.2) 的版本不兼容,需要添加application.yml相关配置

3.application.yml

  1. spring:
  2. mvc:
  3. pathmatch:
  4. matching-strategy: ant_path_matcher

4.web层接口服务提供

  1. package com.ycx.minoa.wxcontroller;
  2. import io.swagger.annotations.Api;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @Api(tags = "会议OA接口开发测试")
  7. @RestController
  8. public class HelloController {
  9. @GetMapping("/hello")
  10. public String hello(){
  11. return "hello";
  12. }
  13. }
  1. @Api(tags = "会议OA小程序接口列表")
  2. @RestController
  3. @RequestMapping("/wx/home")
  4. public class WxHomeController {
  5. @Autowired
  6. private InfoMapper infoMapper;
  7. @ApiOperation("会议OA首页数据加载")
  8. @GetMapping("/index")
  9. public Object index(@RequestBody Info info) {
  10. List<Info> infoList = infoMapper.list(info);
  11. Map<Object, Object> data = new HashMap<Object, Object>();
  12. data.put("infoList",infoList);
  13. return ResponseUtil.ok(data);
  14. }
  15. }

  1. package com.ycx.minoa.model;
  2. import io.swagger.annotations.ApiModel;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import java.util.Date;
  5. @ApiModel(description = "会议信息")
  6. public class Info {
  7. @ApiModelProperty(value = "会议ID", name="id", required = false)
  8. private Long id;
  9. @ApiModelProperty(value = "会议标题", name="title", required = false)
  10. private String title;
  11. @ApiModelProperty(value = "会议内容", name="content", required = false)
  12. private String content;
  13. @ApiModelProperty(value = "参与者", name="canyuze", required = false)
  14. private String canyuze;
  15. @ApiModelProperty(value = "列席人员", name="liexize", required = false)
  16. private String liexize;
  17. @ApiModelProperty(value = "主持人", name="zhuchiren", required = false)
  18. private String zhuchiren;
  19. @ApiModelProperty(value = "会议地点", name="location", required = false)
  20. private String location;
  21. @ApiModelProperty(value = "会议开始时间", name="starttime", required = false)
  22. private Date starttime;
  23. @ApiModelProperty(value = "会议结束时间", name="endtime", required = false)
  24. private Date endtime;
  25. @ApiModelProperty(value = "附件", name="fujian", required = false)
  26. private String fujian;
  27. @ApiModelProperty(value = "会议状态", name="state", required = false)
  28. private Integer state;
  29. @ApiModelProperty(value = "审批人", name="auditperson", required = false)
  30. private String auditperson;
  31. @ApiModelProperty(value = "审批时间", name="audittime", required = false)
  32. private Date audittime;
  33. @ApiModelProperty(value = "会议座位图片", name="seatpic", required = false)
  34. private String seatpic;
  35. @ApiModelProperty(value = "备注", name="remark", required = false)
  36. private String remark;
  37. public Info(Long id, String title, String content, String canyuze, String liexize, String zhuchiren, String location, Date starttime, Date endtime, String fujian, Integer state, String auditperson, Date audittime, String seatpic, String remark) {
  38. this.id = id;
  39. this.title = title;
  40. this.content = content;
  41. this.canyuze = canyuze;
  42. this.liexize = liexize;
  43. this.zhuchiren = zhuchiren;
  44. this.location = location;
  45. this.starttime = starttime;
  46. this.endtime = endtime;
  47. this.fujian = fujian;
  48. this.state = state;
  49. this.auditperson = auditperson;
  50. this.audittime = audittime;
  51. this.seatpic = seatpic;
  52. this.remark = remark;
  53. }
  54. public Info() {
  55. super();
  56. }
  57. public Long getId() {
  58. return id;
  59. }
  60. public void setId(Long id) {
  61. this.id = id;
  62. }
  63. public String getTitle() {
  64. return title;
  65. }
  66. public void setTitle(String title) {
  67. this.title = title;
  68. }
  69. public String getContent() {
  70. return content;
  71. }
  72. public void setContent(String content) {
  73. this.content = content;
  74. }
  75. public String getCanyuze() {
  76. return canyuze;
  77. }
  78. public void setCanyuze(String canyuze) {
  79. this.canyuze = canyuze;
  80. }
  81. public String getLiexize() {
  82. return liexize;
  83. }
  84. public void setLiexize(String liexize) {
  85. this.liexize = liexize;
  86. }
  87. public String getZhuchiren() {
  88. return zhuchiren;
  89. }
  90. public void setZhuchiren(String zhuchiren) {
  91. this.zhuchiren = zhuchiren;
  92. }
  93. public String getLocation() {
  94. return location;
  95. }
  96. public void setLocation(String location) {
  97. this.location = location;
  98. }
  99. public Date getStarttime() {
  100. return starttime;
  101. }
  102. public void setStarttime(Date starttime) {
  103. this.starttime = starttime;
  104. }
  105. public Date getEndtime() {
  106. return endtime;
  107. }
  108. public void setEndtime(Date endtime) {
  109. this.endtime = endtime;
  110. }
  111. public String getFujian() {
  112. return fujian;
  113. }
  114. public void setFujian(String fujian) {
  115. this.fujian = fujian;
  116. }
  117. public Integer getState() {
  118. return state;
  119. }
  120. public void setState(Integer state) {
  121. this.state = state;
  122. }
  123. public String getAuditperson() {
  124. return auditperson;
  125. }
  126. public void setAuditperson(String auditperson) {
  127. this.auditperson = auditperson;
  128. }
  129. public Date getAudittime() {
  130. return audittime;
  131. }
  132. public void setAudittime(Date audittime) {
  133. this.audittime = audittime;
  134. }
  135. public String getSeatpic() {
  136. return seatpic;
  137. }
  138. public void setSeatpic(String seatpic) {
  139. this.seatpic = seatpic;
  140. }
  141. public String getRemark() {
  142. return remark;
  143. }
  144. public void setRemark(String remark) {
  145. this.remark = remark;
  146. }
  147. }

5.测试结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/373143
推荐阅读
相关标签
  

闽ICP备14008679号