前言技术之swagger
创始人
2024-05-09 15:33:47
0

一.前后端分离的特点

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

后台: 负责业务处理

前端: 负责显示逻辑

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

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

二.在没有swagger之前

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

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

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

三.swagger的作用

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

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

四.swagger的优点

号称时最流行的API框架

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

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

支持多语言

五.集成swagger

5.1 新建springboot项目

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

5.2 集成swagger

1.pom.xml



io.springfox
swagger
2.9.2



io.springfox
springfox-swagger-ui
2.9.2

2.编写swagger配置类

package com.ycx.swagger.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket createRestApi(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.ant("/**")) //项目名.build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("SwaggerDemoAPIDOC").description("SwaggerDemoAPIDOC").version("1.0").termsOfServiceUrl("https://www.baidu.com").build();}
}

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

5.3 开发一个controller用于测试

package com.ycx.swagger.web;import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;//@Api(tags = {"这是swagger入门类","作用2"})
@Api(tags = "这是swagger入门类")
@RestController
@RequestMapping("/swagger")
public class HelloController {
//    @ApiOperation(value = "", tags = "swagger入门方法")@ApiOperation(value = "swagger入门方法")@GetMapping("/hello")public Map hello(){Map map = new HashMap<>();map.put("code",200);map.put("msg","响应成功!!!");return map;}
}

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使用综合案例

package com.ycx.swagger.web;import com.ycx.swagger.dto.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/swagger/api")
@Api(tags = "swagger所有注解的讲解")
public class SwaggerController {@ApiOperation(value = "欢迎信息")@GetMapping("/hello")@ApiImplicitParams({@ApiImplicitParam(name = "name", value = "名称", dataType = "string", paramType = "query", required = true),@ApiImplicitParam(name = "msg", value="消息", dataType = "string", paramType = "query", required = true)})public Object hello(String name, String msg) {Map map = new HashMap<>();map.put("code", 200);map.put("msg", "操作成功");map.put("info",name+":"+msg);return map;}@PostMapping("/register")@ApiOperation("注册用户接口")@ApiResponses({@ApiResponse(code = 5001001,message = "错误1"),@ApiResponse(code = 5001002,message = "错误2"),@ApiResponse(code = 5001003,message = "错误3")})public Object register(User user) {Map map = new HashMap<>();map.put("code", 5001002);map.put("msg", "操作成功");map.put("info",user);return map;}@PutMapping("/edit")@ApiOperation("修改用户信息")public Object edit(@RequestBody User user) {Map map = new HashMap<>();map.put("code", 200);map.put("msg", "操作成功");map.put("info",user);return map;}@DeleteMapping("/delete/{id}")@ApiOperation("删除用户")@ApiImplicitParam(name = "id", value="用户ID", dataType = "string", paramType = "path", required = true)public Object delete(@PathVariable("id") String id) {Map map = new HashMap<>();map.put("code", 200);map.put("msg", "操作成功");map.put("info",id);return map;}
}

package com.ycx.swagger.dto;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;@Data
@ApiModel(description = "用户信息")
public class User {@ApiModelProperty(value = "用户名", name="name", required = true)private String name;@ApiModelProperty(value = "密码", name="passwd", required = true)private String passwd;}

    • 会议OA之swagger

  1. pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.7.7 com.ycxminoa0.0.1-SNAPSHOTminoaDemo project for Spring Boot1.81.2.702.9.8org.springframework.bootspring-boot-starter-jdbcorg.springframework.bootspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.2.1mysqlmysql-connector-java5.1.44runtimeorg.projectlomboklomboktruecom.alibabafastjson${fastjson.version}io.springfoxspringfox-swagger22.9.2io.springfoxspringfox-swagger-ui2.9.2org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombokorg.mybatis.generatormybatis-generator-maven-plugin1.3.2mysqlmysql-connector-java${mysql.version}true

2.swagger的整合配置类

package com.ycx.minoa.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket createRestApi(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).paths(PathSelectors.ant("/**")) //项目名.build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("SwaggerDemoAPIDOC").description("SwaggerDemoAPIDOC").version("1.0").termsOfServiceUrl("https://www.baidu.com").build();}
}

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

3.application.yml

spring:mvc:pathmatch:matching-strategy: ant_path_matcher

4.web层接口服务提供

package com.ycx.minoa.wxcontroller;import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@Api(tags = "会议OA接口开发测试")
@RestController
public class HelloController {@GetMapping("/hello")public String hello(){return "hello";}
}
@Api(tags = "会议OA小程序接口列表")
@RestController
@RequestMapping("/wx/home")
public class WxHomeController {@Autowiredprivate InfoMapper infoMapper;@ApiOperation("会议OA首页数据加载")@GetMapping("/index")public Object index(@RequestBody Info info) {List infoList = infoMapper.list(info);Map data = new HashMap();data.put("infoList",infoList);return ResponseUtil.ok(data);}
}

package com.ycx.minoa.model;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;import java.util.Date;@ApiModel(description = "会议信息")
public class Info {@ApiModelProperty(value = "会议ID", name="id", required = false)private Long id;@ApiModelProperty(value = "会议标题", name="title", required = false)private String title;@ApiModelProperty(value = "会议内容", name="content", required = false)private String content;@ApiModelProperty(value = "参与者", name="canyuze", required = false)private String canyuze;@ApiModelProperty(value = "列席人员", name="liexize", required = false)private String liexize;@ApiModelProperty(value = "主持人", name="zhuchiren", required = false)private String zhuchiren;@ApiModelProperty(value = "会议地点", name="location", required = false)private String location;@ApiModelProperty(value = "会议开始时间", name="starttime", required = false)private Date starttime;@ApiModelProperty(value = "会议结束时间", name="endtime", required = false)private Date endtime;@ApiModelProperty(value = "附件", name="fujian", required = false)private String fujian;@ApiModelProperty(value = "会议状态", name="state", required = false)private Integer state;@ApiModelProperty(value = "审批人", name="auditperson", required = false)private String auditperson;@ApiModelProperty(value = "审批时间", name="audittime", required = false)private Date audittime;@ApiModelProperty(value = "会议座位图片", name="seatpic", required = false)private String seatpic;@ApiModelProperty(value = "备注", name="remark", required = false)private String remark;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) {this.id = id;this.title = title;this.content = content;this.canyuze = canyuze;this.liexize = liexize;this.zhuchiren = zhuchiren;this.location = location;this.starttime = starttime;this.endtime = endtime;this.fujian = fujian;this.state = state;this.auditperson = auditperson;this.audittime = audittime;this.seatpic = seatpic;this.remark = remark;}public Info() {super();}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getCanyuze() {return canyuze;}public void setCanyuze(String canyuze) {this.canyuze = canyuze;}public String getLiexize() {return liexize;}public void setLiexize(String liexize) {this.liexize = liexize;}public String getZhuchiren() {return zhuchiren;}public void setZhuchiren(String zhuchiren) {this.zhuchiren = zhuchiren;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}public Date getStarttime() {return starttime;}public void setStarttime(Date starttime) {this.starttime = starttime;}public Date getEndtime() {return endtime;}public void setEndtime(Date endtime) {this.endtime = endtime;}public String getFujian() {return fujian;}public void setFujian(String fujian) {this.fujian = fujian;}public Integer getState() {return state;}public void setState(Integer state) {this.state = state;}public String getAuditperson() {return auditperson;}public void setAuditperson(String auditperson) {this.auditperson = auditperson;}public Date getAudittime() {return audittime;}public void setAudittime(Date audittime) {this.audittime = audittime;}public String getSeatpic() {return seatpic;}public void setSeatpic(String seatpic) {this.seatpic = seatpic;}public String getRemark() {return remark;}public void setRemark(String remark) {this.remark = remark;}
}

5.测试结果

相关内容

热门资讯

电脑里怎么下载安卓系统,电脑端... 你有没有想过,你的电脑里也能装上安卓系统呢?没错,就是那个让你手机不离手的安卓!今天,就让我来带你一...
索尼相机魔改安卓系统,魔改系统... 你知道吗?最近在摄影圈里掀起了一股热潮,那就是索尼相机魔改安卓系统。这可不是一般的改装,而是让这些专...
安卓系统哪家的最流畅,安卓系统... 你有没有想过,为什么你的手机有时候像蜗牛一样慢吞吞的,而别人的手机却能像风一样快?这背后,其实就是安...
安卓最新系统4.42,深度解析... 你有没有发现,你的安卓手机最近是不是有点儿不一样了?没错,就是那个一直在默默更新的安卓最新系统4.4...
android和安卓什么系统最... 你有没有想过,你的安卓手机到底是用的是什么系统呢?是不是有时候觉得手机卡顿,运行缓慢,其实跟这个系统...
平板装安卓xp系统好,探索复古... 你有没有想过,把安卓系统装到平板上,再配上XP系统,这会是怎样一番景象呢?想象一边享受着安卓的便捷,...
投影仪装安卓系统,开启智能投影... 你有没有想过,家里的老式投影仪也能焕发第二春呢?没错,就是那个曾经陪你熬夜看电影的“老伙计”,现在它...
安卓系统无线车载carplay... 你有没有想过,开车的时候也能享受到苹果设备的便利呢?没错,就是那个让你在日常生活中离不开的iOS系统...
谷歌安卓8系统包,系统包解析与... 你有没有发现,手机更新换代的速度简直就像坐上了火箭呢?这不,最近谷歌又发布了安卓8系统包,听说这个新...
微软平板下软件安卓系统,开启全... 你有没有想过,在微软平板上也能畅享安卓系统的乐趣呢?没错,这就是今天我要跟你分享的神奇故事。想象你手...
coloros是基于安卓系统吗... 你有没有想过,手机里的那个色彩斑斓的界面,背后其实有着一个有趣的故事呢?没错,我要说的就是Color...
安卓神盾系统应用市场,一站式智... 你有没有发现,手机里的安卓神盾系统应用市场最近可是火得一塌糊涂啊!这不,我就来给你好好扒一扒,看看这...
黑莓平板安卓系统升级,解锁无限... 亲爱的读者们,你是否还记得那个曾经风靡一时的黑莓手机?那个标志性的全键盘,那个独特的黑莓体验,如今它...
安卓文件系统采用华为,探索高效... 你知道吗?最近安卓系统在文件管理上可是有了大动作呢!华为这个科技巨头,竟然悄悄地给安卓文件系统来了个...
深度系统能用安卓app,探索智... 你知道吗?现在科技的发展真是让人惊叹不已!今天,我要给你揭秘一个超级酷炫的话题——深度系统能用安卓a...
安卓系统的分区类型,深度解析存... 你有没有发现,你的安卓手机里藏着不少秘密?没错,就是那些神秘的分区类型。今天,就让我带你一探究竟,揭...
安卓系统铠无法兑换,揭秘无法兑... 最近是不是有很多小伙伴在玩安卓系统的游戏,突然发现了一个让人头疼的问题——铠无法兑换!别急,今天就来...
汽车安卓系统崩溃怎么刷,一键刷... 亲爱的车主朋友们,你是否曾遇到过汽车安卓系统崩溃的尴尬时刻?手机系统崩溃还能重启,但汽车系统崩溃了,...
miui系统可以刷安卓p系统吗... 亲爱的手机控们,你是否对MIUI系统情有独钟,同时又对安卓P系统的新鲜功能垂涎欲滴?今天,就让我带你...
android系统和安卓哪个好... 说到手机操作系统,你有没有想过,Android系统和安卓哪个更好用呢?这可是个让无数手机用户纠结的问...