Swagger|SpringBoot集成Swagger用以生成API文档

news2024/10/7 13:23:09

框架简介

文档效果图

Swagger的作用:
自动生成强大的RESTful API文档,减少开发人员的工作量。使用Swagger,只需在代码中添加一些注解即可生成API接口文档,不需要手动编写API接口文档,这减少了开发人员的工作量。
提供API文档的同步更新:通过使用Swagger,API文档可以与代码同步更新,保持文档与实际代码的一致性,方便团队的沟通和协作。
提供API文档的可视化展示:生成的API文档页面具有良好的可视化效果,使API接口的信息更加易于理解和使用。
提供API接口的测试功能:生成的API文档页面带有测试功能,可以在文档中直接进行API接口的测试,方便开发人员进行接口调试和验证。
需要注意的是,有人认为使用Swagger与代码耦合在一起,这一点在不同的团队和项目中可能会有不同的看法。有些人认为这种方式提供了便利和一致性,而有些人则认为它可能导致代码的臃肿和维护的困难。因此,对于是否使用Swagger,应根据具体的项目需求和团队的偏好进行评估和决策。

详细步骤

pom文件中添加Swagger依赖

 <!--springboot 集成 swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

👆👆👆请使用以上版本依赖即可👆👆👆

👇👇👇直接使用以下版本会报错(以下依赖不用添加进pom文件),具体原因请看文章底部问题解决👇👇👇

<!-- swagger依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

编写Swagger的配置类

import io.swagger.annotations.ApiOperation;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@EnableSwagger2 //开启对Swagger2的支持
@Configuration //声明当前类是一个配置类
public class SwaggerConfig {
 
    //在Spring容器中配置一个Bean对象
    @Bean
    public Docket docket() {
        //链式编程(构建器模式),基本是固定
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true) //设置false即关闭文档
                .apiInfo(apiInfo())
                .select()
                //扫描带有ApiOperation注解的所有方法,为它们生成API接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }
 
    //创建API的基本信息,自定义即可
    private ApiInfo apiInfo() {
        //链式编程(构建器模式),基本是固定
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("一些内容")
                .termsOfServiceUrl("https://blog.csdn.net/weixin_45966550")
                .contact(new Contact("PaperFish","https://github.com/PaperFish233","PaperFish@163.com"))
                .version("1.0.0")
                .build();
    }
}

Swagger常用注解参数

详细注解可参考官方:https://github.com/swagger-api/swagger-core/wiki/Annotations

Swagger常用注解:
@Api:用在类上,说明该类的作用;
@ApiOperation:用在方法上,说明方法的作用;
@ApiImplicitParams:用在方法上包含一组参数说明;

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面:
          paramType:参数放在哪个地方;
                    header–>请求参数的获取:@RequestHeader;
                    query–>请求参数的获取:@RequestParam;
                    path–>请求参数的获取:@PathVariable (用于restful接口);
                    body(不常用);
                    form(不常用);
          name:参数名;
          dataType:参数类型;
          required:参数是否必须传;
          value:参数的意思;
          defaultValue:参数的默认值;

@ApiResponses:用于表示一组响应;
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息;
          code:数字,例如400;
          message:信息,例如 “请求参数不合法”;
          response:抛出异常的类;

@ApiIgnore:使用该注解忽略这个API,在页面上不显示;
@ApiModel:描述一个Model的信息;
@ApiModelProperty:描述一个model的属性;

swagger安全性问题: 正式上线的时候,建议关闭swagger。

在控制层需要生成API的类及方法上添加注解

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.neusoft.elementplusboot.po.Users;
import com.neusoft.elementplusboot.service.UsersService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(tags = "用户信息相关接口")
@RestController
@RequestMapping("/usersController")
public class UsersController {

	@Autowired
	UsersService usersService;

	@ApiOperation(value = "分页获取所有用户信息", notes = "根据页码及页中数量获取用户信息", response = Users.class, responseContainer = "Map")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "page", value = "页码", dataType = "int", required = true),
			@ApiImplicitParam(paramType = "query", name = "pageSize", value = "页中数量", dataType = "int", required = true),
			@ApiImplicitParam(paramType = "query", name = "uname", value = "用户姓名", dataType = "String") })
	@ApiResponses({ @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 201, message = "已创建新的资源"),
			@ApiResponse(code = 400, message = "缺少必要的请求参数"), @ApiResponse(code = 401, message = "请求路径没有响应的权限"),
			@ApiResponse(code = 403, message = "请求路径被隐藏不能访问"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径错误"),
			@ApiResponse(code = 405, message = "请求方法不支持"), })
	@GetMapping("/getAllUsers")
	public Map<String, Object> getAllUsers(int page, int pageSize, String uname) {
		// int startpPage = (page - 1) * pageSize;
		Page<Object> startPage = PageHelper.startPage(page, pageSize);
		List<Users> usersList = usersService.getAllUsers(uname);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", usersList); // 记录返回内容
		map.put("total", startPage.getTotal()); // 记录数据条数

		return map;
	}

	@ApiOperation(value = "新增用户", notes = "新增用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "uid", value = "编号", dataType = "Integer", required = true),
			@ApiImplicitParam(paramType = "query", name = "uname", value = "姓名", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "uage", value = "年龄", dataType = "Integer", required = true),
			@ApiImplicitParam(paramType = "query", name = "usex", value = "性别", dataType = "Integer", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 201, message = "已创建新的资源"),
			@ApiResponse(code = 400, message = "缺少必要的请求参数"), @ApiResponse(code = 401, message = "请求路径没有响应的权限"),
			@ApiResponse(code = 403, message = "请求路径被隐藏不能访问"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径错误"),
			@ApiResponse(code = 405, message = "请求方法不支持"), })
	@PostMapping("/saveUsers")
	public int saveUsers(Users users) {
		return usersService.saveUsers(users);
	}

	@ApiOperation(value = "更新用户", notes = "更新用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "uid", value = "编号", dataType = "Integer", required = true),
			@ApiImplicitParam(paramType = "query", name = "uname", value = "姓名", dataType = "String"),
			@ApiImplicitParam(paramType = "query", name = "uage", value = "年龄", dataType = "Integer"),
			@ApiImplicitParam(paramType = "query", name = "usex", value = "性别", dataType = "Integer") })
	@ApiResponses({ @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 201, message = "已创建新的资源"),
			@ApiResponse(code = 400, message = "缺少必要的请求参数"), @ApiResponse(code = 401, message = "请求路径没有响应的权限"),
			@ApiResponse(code = 403, message = "请求路径被隐藏不能访问"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径错误"),
			@ApiResponse(code = 405, message = "请求方法不支持"), })
	@PutMapping("/updateUsers")
	public int updateUsers(Users users) {
		return usersService.updateUsers(users);
	}

	@ApiOperation(value = "删除用户", notes = "删除用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "uid", value = "编号", dataType = "Integer", required = true) })
	@ApiResponses({ @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 201, message = "已创建新的资源"),
			@ApiResponse(code = 400, message = "缺少必要的请求参数"), @ApiResponse(code = 401, message = "请求路径没有响应的权限"),
			@ApiResponse(code = 403, message = "请求路径被隐藏不能访问"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径错误"),
			@ApiResponse(code = 405, message = "请求方法不支持"), })
	@DeleteMapping("/deleteUsers")
	public int deleteUsers(Integer uid) {
		return usersService.deleteUsers(uid);
	}

}

问题解决

报错Failed to start bean ‘documentationPluginsBootstrapper’

报错可能原因:SpringBoot版本和Swagger版本不匹配导致(Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的则是PathPatternMatcher)

解决方法:
1、修改SpringBoot的版本,使用早期版本;
2、yml配置文件中添加如下配置(设置"ant_path_matcher"作为匹配策略):

spring:
    mvc:
        pathmatch:
            matching-strategy: ant_path_matcher

报错java.lang.NumberFormatException: For input string: “”

报错可能原因:@ApiImplicitParams注解属性中的参数类型出了问题,空字符串""无法转成Number。(swagger版本的问题,之前使用的是io.springfox:springfox-swagger2:2.9.2的版本,而该版本依赖了swagger-models的1.5.20版本(会导致报此错),深挖原因是1.5.20版本中的example只判断了是否为null,没有判断是否为空串;1.5.21版本对两者都进行了判断。)

解决方法:
1、在注解中为int属性的参数添加一个默认值属性(example = “1”):

@ApiImplicitParams(@ApiImplicitParam(name = "id",value = "编号",dataType = "int",required = true,example = "1"))

2、排除springfox-swagger2中的swagger-models依赖,导入io.swagger:swagger-models的1.5.21版本。将之前导入pom文件的两个依赖换成如下即可:

 <!--springboot 集成 swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

结语

仅自学留档以及整合,部分内容参考自:
http://t.csdn.cn/N8dr1 | http://t.csdn.cn/jSgPP | http://t.csdn.cn/OAIN9

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/705876.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

西安石油大学 C++期末考试 重点知识点+题目复习(下)

析构函数调用顺序 析构函数的调用顺序与对象的创建和销毁顺序相反。 对于单个对象&#xff0c;当对象的生命周期结束时&#xff08;例如离开作用域&#xff09;&#xff0c;会调用其析构函数。因此&#xff0c;析构函数会在对象销毁之前被调用。 对于类的成员对象&#xff0…

软件工程期末复习-软件设计模式与体系结构-体系结构

目录 软件体系结构概述一、调用-返回风格软件体系结构概念主程序-子程序软件体系结构自顶向下的设计方法的问题结构化设计的优缺点面向对象体系结构面向对象设计的优缺点主程序-子程序与面向对象体系结构相似差异 课程作业 二、数据流风格软件体系结构概念控制流 vs. 数据流数据…

【第一章 flutter学习入门之环境配置】

flutter环境安装 文章目录 flutter环境安装前言一、环境变量配置二、下载Flutter SDK三.排除错误 安装依赖四. 设置Android模拟器五.安装插件VScode打开flutter项目 前言 本文是针对Windows系统环境配置flutter 需要git环境依赖&#xff0c;这里就不做过多赘述 一、环境变量配…

PFASs在固体-溶液体系中分配系数

一、对于PFASs在土壤-溶液体系中的吸附行为,可以用土壤-水分配系数(Kd,L/kg)来表征[1-3]。 Cs为沉积物(sediment)中PFAAs的浓度(ng/g dw);Cw为水(water)中单个PFAAs的浓度(μg/L)。 以往许多研究发现,Ksp与沉积物的有机碳组分有关,表明有机质含量是影响沉积物和孔…

【书】《Python全栈测试开发》——浅谈我所理解的『自动化』测试

目录 1. 自动化测试的What and Why?1.1 What1.2 Why2. 自动化的前戏需要准备哪些必备技能?3. 自动化测试类型3.1 Web自动化测试3.1.1 自动化测试设计模式3.1.2 自动化测试驱动方式3.1.3 自动化测试框架3.2 App自动化测试3.3 接口自动化测试4. 自动化调优《Python全栈测试开发…

PPO算法基本原理及流程图(KL penalty和Clip两种方法)

PPO算法基本原理 PPO&#xff08;Proximal Policy Optimization&#xff09;近端策略优化算法&#xff0c;是一种基于策略&#xff08;policy-based&#xff09;的强化学习算法&#xff0c;是一种off-policy算法。 详细的数学推导过程、为什么是off-policy算法、advantage函数…

47. Compose自定义绘制日历-1

有个日历的需求, 自己实现一下简单的 生成数据 private fun initData() {val listOfCalendar mutableListOf<CalendarData>()val calendar Calendar.getInstance()val todayYear calendar.get(Calendar.YEAR)val todayMonth calendar.get(Calendar.MONTH)val today…

单机和分布式有什么区别?分布式系统相比单机系统的优势在哪里?

写在前面 本文隶属于专栏《大数据理论体系》&#xff0c;该专栏为笔者原创&#xff0c;引用请注明来源&#xff0c;不足和错误之处请在评论区帮忙指出&#xff0c;谢谢&#xff01; 本专栏目录结构和文献引用请见《大数据理论体系》 思维导图 1. 资源共享 单机系统是指只有一…

springboot项目通过nginx访问ftp服务器文件

前文 本来准备记录一下。项目中遇到的springboot项目访问ftp服务器图片、视频问题的&#xff0c;想在我自己服务器上重新部署一遍&#xff0c;然后发现&#xff0c;执行docker的时候报错了。具体报错原因如下&#xff1a; 原因是我重启了一下服务器 Cannot connect to the Do…

ChatGPT实战:生成演讲稿

当众发言&#xff08;演讲&#xff09;是一种传达信息、观点和情感的重要方式。通过演讲&#xff0c;人们可以在公共场合表达自己的观点&#xff0c;向观众传递自己的知识和经验&#xff0c;激发听众的思考和行动。无论是商务演讲、学术讲座还是政治演说&#xff0c;演讲稿的写…

linux查找文件内容命令之grep -r ‘关键字‘

目录 grep命令介绍参数选项 grep命令的使用1. 在指定的文件中查找包含的关键字2. 在指定目录下多个文件内容中查找包含的关键字3.在追加的文件内容中查找关键字4. 统计文件中关键字出现的次数5. vi或vim打开的文件查找关键字(补充) 总结 grep命令介绍 Linux操作系统中 grep 命…

EventBus源码分析

差不多两年没写博客了&#xff0c;最近想着要找工作了&#xff0c;打算复习下一些常用的开源库&#xff0c;也是这篇博客的由来&#xff5e; EventBus使用非常简单 参考&#xff1a;github 再贴一张官网的图 一、示例代码 示例代码是为了便于理解后面注解处理器生成代码的处…

1. MyBatis 整体架构

作为正式内容的第一篇&#xff0c;本次不会介绍具体的技术&#xff0c;而是先从全局视角上对 MyBatis 做一个俯瞰&#xff0c;了解 MyBatis 项目工程的组织结构&#xff0c;以及内部的核心功能模块。 工程结构 打开 MyBatis 的 Github 地址&#xff0c;就可以看到其代码工程结…

C语言:打印用 * 组成的带空格直角三角形图案

题目&#xff1a; 多组输入一个整数&#xff08;2~20&#xff09;&#xff0c;表示直角三角形直角边的长度&#xff0c;即 * 的数量&#xff0c;也表示输出行数。 思路&#xff1a; 总体思路&#xff1a; 找到规律&#xff1a; 行数 列数 < 三角形长度 - 1 打印 两个空格…

一步一步学OAK之十四: 获取OAK设备信息

这一节我们通过调用DepthAI API 来获取OAK设备信息 目录 DeviceBootloader简介获取OAK设备信息的方法Setup 1: 创建文件Setup 2: 安装依赖Setup 3: 导入需要的包Setup 4: 获取可用设备Setup 5: 判断infos的长度Setup 6: 遍历infosSetup 7: 打印提示消息Setup 8: 连接设备Setup…

html_4——知识总结

html_4——知识总结 一、计算机基础知识二、html4总结2.1 html基本结构2.2 全局属性-id,class,style,dir,title,lang2.3 格式排版标签-div,p,h1-h6,br,hr,pre2.4 文本标签-span,en,strong,del,ins,sub,sup2.5 图片标签-img:src,alt,width,height,boder2.6 超链接-a:herf,target…

内部函数和外部函数

文章目录 怎么来的&#xff1f;内部函数外部函数明确一下内外的概念&#xff1a;外部函数的实例fgets()函数 怎么来的&#xff1f; 函数本质上是全局的&#xff0c;因为定义一个函数的目的就是这个函数与其他函数之间相互调用&#xff0c;如果不声明的话&#xff0c;一个函数既…

YouTube正测试屏蔽“广告拦截器”,以确保其广告收入

YouTube目前正在进行一项全球范围内的小规模测试&#xff0c;警告用户关掉他们的广告屏蔽器&#xff0c;否则将被限制观看视频的次数。 周三&#xff08;6月28日&#xff09;&#xff0c;Reddit的一位用户发现&#xff0c;在使用YouTube时弹出了一个窗口&#xff0c;提示该用户…

Cali3F: Calibrated Fast Fair Federated Recommendation System

Decentralized Collaborative Learning Framework for Next POI Recommendation 标定的&#xff08;校准的&#xff09;快速公平联邦推荐系统 1. What does literature study? 提出一个经过校准的快速而公平的联邦推荐框架Cali3F&#xff0c;通过集群内参数共享解决了收敛问…

创新引领未来:RFID技术在汽车装配中的智能革命

射频识别&#xff08;RFID&#xff09;技术作为一种自动识别技术&#xff0c;已经在许多领域得到广泛应用。在汽车装配领域&#xff0c;RFID技术的应用可以提高装配过程的效率、降低人工错误率&#xff0c;并帮助实现自动化和智能化生产。本文将介绍RFID技术在汽车装配中的应用…