热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

springboot整合Swagger2的使用

Swagger2相较于传统Api文档的优点手写Api文档的几个痛点:文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。接口返回结果不明确不能直接在线测试接口,通

Swagger2相较于传统Api文档的优点


手写Api文档的几个痛点:

文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。

接口返回结果不明确

不能直接在线测试接口,通常需要使用工具,比如postman

接口文档太多,不好管理

Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。

可以直接使用Swagger editor编写接口文档,我们这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。

依赖文件


io.springfox
springfox-swagger2
2.6.1


io.springfox
springfox-swagger-ui
2.6.1

配置类

package com.boss.hr.train.fishkkmybatis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
/**
* @author fishkk
* @version 1.0.0
* @since
*/
@Configuration
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.boss.hr.train.fishkkmybatis.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("fishkk的Swagger")
.version("1.0")
.build();
}
}

在启动函数出天价@EnableSwagger2,到这里就可以正常的使用Swagger2 了

Swagger2 的具体使用

package com.boss.hr.train.fishkkmybatis.controller;
import com.boss.hr.train.fishkkmybatis.annotation.Logg;
import com.boss.hr.train.fishkkmybatis.entity.Dictionary;
import com.boss.hr.train.fishkkmybatis.entity.Result;
import com.boss.hr.train.fishkkmybatis.enums.DictionaryEnum;
import com.boss.hr.train.fishkkmybatis.exception.BaseException;
import com.boss.hr.train.fishkkmybatis.service.impl.DictionaryServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @author fishkk
* @version 1.0.0
* @since 2019/7/27
*/
@RestController
@RequestMapping(value = "/dic")
@CrossOrigin
public class DictionaryController {
/**
* Redis 缓存
*/
@Resource
private RedisTemplate redisTemplate;
@Resource
private DictionaryServiceImpl dictionaryService;
private List list;
/**
* 创建字典实体
* @author fishkk
* @since 2017/7/25
* @param dictionary 字典实体
* @return Dictionary 放回创建的字典实体
*/
@ApiOperation(value="创建字典", notes="根据Dictionary对象创建字典")
@ApiImplicitParam(name = "dictionary", value = "字典详细实体dictionary", required = true, dataType = "Dictionary")
@PostMapping(value = "/insert")
public Result insertDic(@Valid Dictionary dictionary, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return Result.error(DictionaryEnum.ERROR_INPUT);
}
dictionaryService.insert(dictionary);
return Result.success(dictionary);
}
/**
* 根据主键查找字典
* @author fishkk
* @since 2019/7/25
* @param id 主键id
* @return dictionary查找到的实体对象
*/
@ApiOperation(value = "获取字典信息",notes = "根据id获取字典信息")
@ApiImplicitParam(name = "id",value = "字典id",required = true, dataType = "Long", paramType = "path")
@GetMapping(value = "/dic")
public Result findById(@RequestParam(value = "id") Integer id){
if (list == null){
list = dictionaryService.selectAll();
for (Dictionary x:list) {
long time = new Random().nextInt(10);
redisTemplate.opsForValue().set(x.getCategoryId(),x,12,TimeUnit.HOURS);
}
}
if (redisTemplate.opsForValue().get(id) != null){
return Result.success(redisTemplate.opsForValue().get(id));
}
redisTemplate.opsForValue().set(id,dictionaryService.selectByPrimaryKey(id),12,TimeUnit.HOURS);
return Result.success(dictionaryService.selectByPrimaryKey(id));
}
/**
* 根据主键删除字典
* @author fishkk
* @since 2019/7/25
* @param id 字典主键
*/
@ApiOperation(value = "根据id删除单个字典表",notes = "根据id删除字典")
@ApiImplicitParam(name = "id",value = "用户id",required = true, dataType = "Long", paramType = "path")
@GetMapping(value = "/remove/{id}")
public Result deleteById(@PathVariable("id") Integer id){
dictionaryService.deleteByPrimaryKey(id);
return Result.success(null);
}
/**
* 更新字典对象
* @author fishkk
* @since 2019/7/26
* @param dictionary 修改过的字典对象
*/
@ApiOperation(value="更新字典", notes="根据Dictionary更新对应的字典")
@ApiImplicitParam(name = "dictionary", value = "字典详细实体dictionary", required = true, dataType = "Dictionary")
@PostMapping(value = "/updata")
public Result updata(@Valid Dictionary dictionary, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return Result.error(DictionaryEnum.ERROR_INPUT);
}
dictionaryService.updateByPrimaryKey(dictionary);
return Result.success(null);
}
/**
* 根据字典名查询
* @author fishkk
* @since 2019/7/28
* @param name 字典名
*/
@GetMapping(value = "/get/{name}")
public Result findByName(@PathVariable("name") String name ){
return Result.success(dictionaryService.findByName(name));
}
/**
* 根据字典类型查询
* @author fishkk
* @since 2019/7/28
* @param type 字典类型
*/
@GetMapping(value = "/gettype/{type}")
public Result findByType(@PathVariable("type") String type){
return Result.success(dictionaryService.findByType(type));
}
/**
* 获取全部对象
* @author fishkk
* @since 2019/7/28
*/
@Logg
@GetMapping(value = "/getall")
public Result findByType(){
//throw new BaseException(DictionaryEnum.NOT_FOUND);
return Result.success(dictionaryService.selectAll());
// Float a = null;
// Float b = Float.intBitsToFloat(11);
// System.out.println(a + b);
// return null;
}
}

启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html

技术分享图片

可以看到上诉类似的结果,我的项目启动太麻烦了含SpringCloud 就不展示了。

Swagger2的注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。


  • @Api:修饰整个类,描述Controller的作用

  • @ApiOperation:描述一个类的一个方法,或者说一个接口

  • @ApiParam:单个参数描述

  • @ApiModel:用对象来接收参数

  • @ApiProperty:用对象接收参数时,描述对象的一个字段

  • @ApiResponse:HTTP响应其中1个描述

  • @ApiResponses:HTTP响应整体描述

  • @ApiIgnore:使用该注解忽略这个API

  • @ApiError :发生错误返回的信息

  • @ApiImplicitParam:一个请求参数

  • @ApiImplicitParams:多个请求参数


推荐阅读
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 本文介绍了通过ABAP开发往外网发邮件的需求,并提供了配置和代码整理的资料。其中包括了配置SAP邮件服务器的步骤和ABAP写发送邮件代码的过程。通过RZ10配置参数和icm/server_port_1的设定,可以实现向Sap User和外部邮件发送邮件的功能。希望对需要的开发人员有帮助。摘要长度:184字。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • 本文介绍了指针的概念以及在函数调用时使用指针作为参数的情况。指针存放的是变量的地址,通过指针可以修改指针所指的变量的值。然而,如果想要修改指针的指向,就需要使用指针的引用。文章还通过一个简单的示例代码解释了指针的引用的使用方法,并思考了在修改指针的指向后,取指针的输出结果。 ... [详细]
  • 在project.properties添加#Projecttarget.targetandroid-19android.library.reference.1..Sliding ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • CentOS 7部署KVM虚拟化环境之一架构介绍
    本文介绍了CentOS 7部署KVM虚拟化环境的架构,详细解释了虚拟化技术的概念和原理,包括全虚拟化和半虚拟化。同时介绍了虚拟机的概念和虚拟化软件的作用。 ... [详细]
  • 本文介绍了一种解析GRE报文长度的方法,通过分析GRE报文头中的标志位来计算报文长度。具体实现步骤包括获取GRE报文头指针、提取标志位、计算报文长度等。该方法可以帮助用户准确地获取GRE报文的长度信息。 ... [详细]
author-avatar
莫轻松
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有