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实战的更多相关文章

  1. springboot集成swagger实战(基础版)

    1. 前言说明 本文主要介绍springboot整合swagger的全过程,从开始的swagger到Knife4j的进阶之路:Knife4j是swagger-bootstarp-ui的升级版,包括一些 ...

  2. spring-boot 集成 swagger 问题的解决

    spring-boot 集成 swagger 网上有许多关于 spring boot 集成 swagger 的教程.按照教程去做,发现无法打开接口界面. 项目由 spring mvc 迁移过来,是一个 ...

  3. 20190909 SpringBoot集成Swagger

    SpringBoot集成Swagger 1. 引入依赖 // SpringBoot compile('org.springframework.boot:spring-boot-starter-web' ...

  4. SpringBoot集成Swagger,Postman,newman,jenkins自动化测试.

    环境:Spring Boot,Swagger,gradle,Postman,newman,jenkins SpringBoot环境搭建. Swagger简介 Swagger 是一款RESTFUL接口的 ...

  5. springboot集成swagger添加消息头(header请求头信息)

    springboot集成swagger上篇文章介绍: https://blog.csdn.net/qiaorui_/article/details/80435488 添加头信息: package co ...

  6. springboot 集成 swagger 自动生成API文档

    Swagger是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的Web服务.简单来说,Swagger是一个功能强大的接口管理工具,并且提供了多种编程语言的前后端分离解决方案. S ...

  7. SpringBoot集成Swagger接口管理工具

    手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时. 接口返回结果不明确 不能直接在线测试接口,通常需要使用工具,比如postman 接口文档太多,不好管 ...

  8. springboot 集成swagger ui

    springboot 配置swagger ui 1. 添加依赖 <!-- swagger ui --> <dependency> <groupId>io.sprin ...

  9. SpringBoot整合Swagger实战

    源码地址:https://github.com/laolunsi/spring-boot-examples 目前SpringBoot常被用于开发Java Web应用,特别是前后端分离项目.为方便前后端 ...

  10. Java SpringBoot集成RabbitMq实战和总结

    目录 交换器.队列.绑定的声明 关于消息序列化 同一个队列多消费类型 注解将消息和消息头注入消费者方法 关于消费者确认 关于发送者确认模式 消费消息.死信队列和RetryTemplate RPC模式的 ...

随机推荐

  1. 云服务器搭建自己的GitServer!

    云服务器搭建自己的GitServer! 如果你有一台云服务器并想在上面搭建自己的 Git 服务器,你可以使用 Git 自带的 git-shell ,也可以使用像 Gitea.GitLab.Gogs 这 ...

  2. 用CI/CD工具Vela部署Elasticsearch + C# 如何使用

    Vela 除了可以帮我们编译.部署程序,利用它的docker部署功能,也能用来部署其他线上的docker镜像,例如部署RabbitMQ.PostgreSql.Elasticsearch等等,便于集中管 ...

  3. spring——DI_依赖注入

    Spring的注入方式 Dependency Injection 概念 依赖注入(Dependency Injection) 依赖:指Bean对象的创建依赖于容器,Bean对象的依赖资源 注入:指Be ...

  4. SQLServer 执行计划的简单学习和与类型转换的影响

    SQLServer 执行计划的简单学习和与类型转换的影响 背景 最近一直在看SQLServer数据库 索引.存储.还有profiler的使用 并且用到了 deadlock graph 但是感觉还是不太 ...

  5. [转帖]数据库的快照隔离级别(Snapshot Isolation)

    https://www.cnblogs.com/gered/p/10251744.html 总结:已提交读快照只影响语句级别的锁定行为,而快照隔离影响整个事务.  转自:https://www.cnb ...

  6. [转帖]【最佳实践】prometheus 监控 sql server (使用sql_exporter)

    https://www.cnblogs.com/gered/p/13535212.html 目录 [0]核心参考 [简述] [1]安装配置 sql_exporter [1.1]下载解压 sql_exp ...

  7. [转帖]Prometheus监控系统存储容量优化攻略,让你的数据安心保存!

    云原生监控领域不可撼动,Prometheus 是不是就没缺点?显然不是. 一个软件如果什么问题都想解决,就会导致什么问题都解决不好.所以Prometheus 也存在不足,广受诟病的问题就是 单机存储不 ...

  8. [转帖]人人都应该知道的CPU缓存运行效率

    https://zhuanlan.zhihu.com/p/628017496 提到CPU性能,大部分同学想到的都是CPU利用率,这个指标确实应该首先被关注.但是除了利用率之外,还有很容易被人忽视的指标 ...

  9. [转帖]Shell脚本中利用expect实现非交互式

    https://developer.aliyun.com/article/885723?spm=a2c6h.24874632.expert-profile.295.7c46cfe9h5DxWK 简介: ...

  10. [转帖]新一代垃圾回收器ZGC的探索与实践

    1. 引入 1.1 GC之痛 很多低延迟高可用Java服务的系统可用性经常受GC停顿的困扰. GC停顿指垃圾回收期间STW(Stop The World),当STW时,所有应用线程停止活动,等待GC停 ...