Springboot集成Swagger实战
1.介绍
本文将通过实战介绍Springboot如何集成swagger2,以用户管理模块为例,实现项目接口文档的在线管理。
项目源码
本文只列出核心部分,详细请看源码:
https://gitee.com/indexman/boot_swagger_demo
2.Swagger是干什么的?
Swagger 是一个用于生成、描述和调用 RESTful 接口的 Web 服务。通俗的来讲,Swagger 就是将项目中所有(想要暴露的)接口展现在页面上,并且可以进行接口调用和测试的服务。
官网地址:https://swagger.io/
其主要作用:
在线API文档:将项目中所有的接口展现在页面上,这样后端程序员就不需要专门为前端使用者编写专门的接口文档。
实时更新:当接口更新之后,只需要修改代码中的 Swagger 描述就可以实时生成新的接口文档了,从而规避了接口文档老旧不能使用的问题。
接口测试:通过 Swagger 页面,我们可以直接进行接口调用,降低了项目开发阶段的调试成本。
3.开发步骤
闲言少叙,直奔主题。
3.1 添加pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.laoxu.demo</groupId>
<artifactId>boot_swagger_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot_swagger_demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2 修改启动类,添加@EnableSwagger2
@EnableSwagger2
@SpringBootApplication
public class BootSwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootSwaggerDemoApplication.class, args);
}
}
3.3 编写配置类
@Configuration
public class Swagger2Config {
@Bean
public Docket adminApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("")
.apiInfo(adminApiInfo())
.select()
.paths(Predicates.and(PathSelectors.regex("/api/.*")))
.build();
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title("用户管理系统-API文档")
.description("本文档描述了用户管理系统接口定义")
.version("1.0")
.contact(new Contact("test", "http//www.baidu.com", "indeman@126.com"))
.build();
}
}
3.4 添加User实体
@ApiModel(value="User对象", description="用户")
@Data
public class User {
private int id;
private String name;
private String city;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date birthday;
public User(){}
public User(int id, String name, String city, Date birthday) {
this.id = id;
this.name = name;
this.city = city;
this.birthday = birthday;
}
}
3.5 添加用户接口
@Api(description="用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
UserService userService;
@ApiOperation("根据ID查询用户")
@GetMapping("/{id}")
public ResultBean getOne(@ApiParam(name="id",value = "用户ID",required = true)
@PathVariable Integer id){
User user = userService.getById(id);
ResultBean result = new ResultBean(0,"查询成功",1, user);
return result;
}
@ApiOperation("分页查询")
@GetMapping("/list")
public ResultBean list(@ApiParam(name="页码",value = "page",required = false)
@RequestParam(defaultValue = "1") Integer page,
@ApiParam(name="页行数",value = "limit",required = false)
@RequestParam(defaultValue = "10") Integer limit){
List<User> users = userService.getPager(page,limit);
int count = userService.getAllUsers().size();
ResultBean result = new ResultBean(0,"查询成功",count,users);
return result;
}
@ApiOperation("修改用户")
@PostMapping("/save")
public ResultBean save(@ApiParam(name="用户实体",value = "user实体",required = true)
@RequestBody User user){
// 判断是新增还是修改
if(user.getId()==0){
userService.addUser(user);
}else{
userService.updateUser(user);
}
return new ResultBean(200,"保存成功",0,"");
}
@ApiOperation("删除用户(多个)")
@PostMapping("/remove")
public ResultBean modify(@ApiParam(name="用户ID数组",value = "ids",required = true)
@RequestBody int[] ids){
userService.delUsers(ids);
return new ResultBean(200,"删除成功",0,"");
}
}
4.启动工程,访问接口文档
访问:http://localhost:9001/swagger-ui.html#/

可以看到用户controller的几个接口定义都在里面了。
5.测试接口
这里挑选第一个接口测试一下,见下图:

可以看到还是很方便的。
Springboot集成Swagger实战的更多相关文章
- springboot集成swagger实战(基础版)
1. 前言说明 本文主要介绍springboot整合swagger的全过程,从开始的swagger到Knife4j的进阶之路:Knife4j是swagger-bootstarp-ui的升级版,包括一些 ...
- spring-boot 集成 swagger 问题的解决
spring-boot 集成 swagger 网上有许多关于 spring boot 集成 swagger 的教程.按照教程去做,发现无法打开接口界面. 项目由 spring mvc 迁移过来,是一个 ...
- 20190909 SpringBoot集成Swagger
SpringBoot集成Swagger 1. 引入依赖 // SpringBoot compile('org.springframework.boot:spring-boot-starter-web' ...
- SpringBoot集成Swagger,Postman,newman,jenkins自动化测试.
环境:Spring Boot,Swagger,gradle,Postman,newman,jenkins SpringBoot环境搭建. Swagger简介 Swagger 是一款RESTFUL接口的 ...
- springboot集成swagger添加消息头(header请求头信息)
springboot集成swagger上篇文章介绍: https://blog.csdn.net/qiaorui_/article/details/80435488 添加头信息: package co ...
- springboot 集成 swagger 自动生成API文档
Swagger是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的Web服务.简单来说,Swagger是一个功能强大的接口管理工具,并且提供了多种编程语言的前后端分离解决方案. S ...
- SpringBoot集成Swagger接口管理工具
手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时. 接口返回结果不明确 不能直接在线测试接口,通常需要使用工具,比如postman 接口文档太多,不好管 ...
- springboot 集成swagger ui
springboot 配置swagger ui 1. 添加依赖 <!-- swagger ui --> <dependency> <groupId>io.sprin ...
- SpringBoot整合Swagger实战
源码地址:https://github.com/laolunsi/spring-boot-examples 目前SpringBoot常被用于开发Java Web应用,特别是前后端分离项目.为方便前后端 ...
- Java SpringBoot集成RabbitMq实战和总结
目录 交换器.队列.绑定的声明 关于消息序列化 同一个队列多消费类型 注解将消息和消息头注入消费者方法 关于消费者确认 关于发送者确认模式 消费消息.死信队列和RetryTemplate RPC模式的 ...
随机推荐
- JS - HTML精确定位
scrollHeight: 获取对象的滚动高度. scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离 scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最 ...
- JS - Array - 在数组的指定下标添加或替换元素 。 也可删除指定下标的元素
一,首先介绍下 js Array对象 中的 splice 方法 . ( splice在英文中是剪接的意思 ) 1,定义和用法 splice() 方法用于插入.删除或替换数组的元素. 注意:这种方法会改 ...
- MyBatis05——一对多和多对一处理
多对一处理 1.数据库表的设计 CREATE TABLE `teacher` ( `id` INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, PRI ...
- MySQL高可用九种方案
有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top 首发博客地址 参考视频 MMM 方案(单主) MySQL 高可用方案之 MM ...
- [转帖]AMD第四代宵龙 9174F 亮眼
https://www.amd.com/zh-hans/processors/epyc-9004-series#%E8%A7%84%E6%A0%BC 型号规格 型号 CPU 核心数量 线程数量 最 ...
- [转贴]Kubernetes之修改NodePort对外映射端口范围
https://www.cnblogs.com/minseo/p/12606326.html k8s默认使用NodePort对外映射端口范围是30000-50000可以通过修改kube-apiserv ...
- 【解决一个小问题】golang 的 `-race`选项导致 unsafe代码 panic
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 为了提升性能,使用 unsafe 代码来重构了凯撒加密的代 ...
- 【K哥爬虫普法】淘宝一亿快递信息泄漏,有人正在盯着你的网购!
我国目前并未出台专门针对网络爬虫技术的法律规范,但在司法实践中,相关判决已屡见不鲜,K 哥特设了"K哥爬虫普法"专栏,本栏目通过对真实案例的分析,旨在提高广大爬虫工程师的法律意识, ...
- 【NSSCTF-Round#16】 Web和Crypto详细完整WP
每天都要加油哦! ------2024-01-18 11:16:55 [NSSRound#16 Basic]RCE但是没有完全RCE <?php error_reporting(0); ...
- go 1.21:cmp
标准库 cmp 原文在这里 go 1.21 新增 cmp 包提供了与有序变脸比较相关的类型和函数. Ordered 定义如下: type Ordered interface { ~int | ~int ...