源码地址:https://github.com/laolunsi/spring-boot-examples

目前SpringBoot常被用于开发Java Web应用,特别是前后端分离项目。为方便前后端开发人员进行沟通,我们在SpringBoot引入了Swagger。

Swagger作用于接口,让接口数据可视化,尤其适用于Restful APi

本节分两部分介绍,第一部分是SpringBoot引入Swagger的两种方式,第二部分是详细介绍在Web接口上应用Swagger的注解。

本篇文章使用SpringBoot 2.1.10.RELEASE和springfox-swagger 2.9.2


一、SpringBoot引入Swagger的两种方式

目前SpringBoot有两种使用Swagger的方式:

  1. 引入swagger原生依赖springfox-swagger2springfox-swagger2-ui
  2. 引入国内Spring4All社区开发的依赖swagger-spring-boot-starter

Spring4All出品的依赖采取配置文件的方式进行配置,而原生依赖是通过java config类来设置的。

1.1 原生配置Swagger

maven依赖:

<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配置类:

/**
* swagger2配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("基于Swagger构建的Rest API文档")
.description("更多请咨询服务开发者eknown")
.contact(new Contact("空夜", "http://www.eknown.cn", "eknown@163.com"))
.termsOfServiceUrl("http://www.eknown.com")
.version("1.0")
.build();
}
}

从这里可以看出Swagger的一个缺点:无法通过SpringBoot的配置文件进行配置,所以配置并不能灵活转变。

spring4all社区出品的swagger-spring-boot-starter可以解决这个问题。


1.2 基于spring4all配置swagger

Spring4All社区的博主程序猿DD和小火两个人开发了Spring Boot Starter Swagger,目前已经在maven官方仓库上线了。

选择第一个,引入该依赖:

<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>

这种方式的Swagger配置是通过application配置文件进行的。下面给出一个示例:

server:
port: 8106
swagger:
base-path: /**
base-package: 'com.example'
title: 'spring-boot-swagger-demo'
description: '基于Swagger构建的SpringBoot RESTApi 文档'
version: '1.0'
contact:
name: '空夜'
url: 'http://www.eknown.cn'
email: 'eknown@163.com'

二、应用Swagger构建接口可视化

2.1 Controller类添加Swagger注解

下面给一个简单的示例:

@Api(tags = "用户管理")
@RestController
@RequestMapping(value = "user")
public class UserController { // 模拟数据库存储的用户
private static Map<Integer, User> userMap; static {
userMap = new ConcurrentHashMap<>();
User user = new User(0, "admin", true, new Date());
userMap.put(user.getId(), user);
} @ApiOperation("列表查询")
@GetMapping(value = "")
public List<User> list() {
return new ArrayList<>(userMap.values());
} @ApiOperation(value = "获取用户详细信息", notes = "路径参数ID")
@GetMapping(value = "{id}")
public User detail(@PathVariable Integer id) {
return userMap.get(id);
} @ApiOperation(value = "新增或更新用户信息", notes = "insert和update共用"
, response = User.class)
@PostMapping(value = "")
public User add(@RequestBody User user) {
if (user == null || user.getId() == null || !StringUtils.isEmpty(user.getName())
|| userMap.containsKey(user.getId())) {
return null;
} user.setUpdateTime(new Date());
userMap.put(user.getId(), user);
return user;
} @ApiOperation(value = "删除用户")
@DeleteMapping(value = "{id}")
public Boolean delete(@ApiParam(name = "用户ID", required = true, example = "100") @PathVariable Integer id) {
if (userMap.containsKey(id)) {
userMap.remove(id);
return true;
} return false;
} }

2.2 参数实体类添加Swagger注解

实体类也需要添加一些注解,以便前端开发人员确定参数的意义、类型、示例等。

@ApiModel(description = "用户类")
public class User { @ApiModelProperty(value = "ID", example = "100")
private Integer id; @ApiModelProperty(value = "姓名", example = "laolunsi")
private String name; @ApiModelProperty(value = "是否启用", example = "1")
private Boolean enable; @ApiModelProperty("更新时间")
private Date updateTime; public User(Integer id, String name, Boolean enable, Date updateTime) {
this.id = id;
this.name = name;
this.enable = enable;
this.updateTime = updateTime;
} // ... ignore getter and setter methods
}

2.3 测试

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

如果存在server.servlet.context-path配置,那么访问地址是http://localhost:port/context-path/swagger-ui.html

这样,接口就一目了然了,swagger还支持在线测试接口,与postman的作用类似。


好,到目前为止,我们已经成功在SpringBoot项目中整合了Swagger,这样前后端开发对接就有了标准!

SpringBoot整合Swagger实战的更多相关文章

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

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

  2. SpringBoot 整合swagger

    springBoot 整合swagger 1.pom.xml 配置 <dependency> <groupId>io.springfox</groupId> < ...

  3. SpringBoot整合Swagger和Actuator

    前言 本篇文章主要介绍的是SpringBoot整合Swagger(API文档生成框架)和SpringBoot整合Actuator(项目监控)使用教程. SpringBoot整合Swagger 说明:如 ...

  4. 【SpringBoot | Swagger】SpringBoot整合Swagger

    SpringBoot整合Swagger 1. 什么是Swagger Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.简单说就是项目跑起来了, ...

  5. springboot整合swagger。完爆前后端调试

    web接口开发时在调试阶段最麻烦的就是参数调试,前端需要咨询后端.后端有时候自己也不是很了解.这时候就会造成调试一次接口就需要看一次代码.Swagger帮我们解决对接的麻烦 springboot接入s ...

  6. springboot整合elasticJob实战(纯代码开发三种任务类型用法)以及分片系统,事件追踪详解

    一 springboot整合 介绍就不多说了,只有这个框架是当当网开源的,支持分布式调度,分布式系统中非常合适(两个服务同时跑不会重复,并且可灵活配置分开分批处理数据,贼方便)! 这里主要还是用到zo ...

  7. SpringBoot 整合 MongoDB 实战介绍

    一.介绍 在前面的文章中,我们详细的介绍了 MongoDB 的配置和使用,如果你对 MongoDB 还不是很了解,也没关系,在 MongoDB 中有三个比较重要的名词:数据库.集合.文档! 数据库(D ...

  8. SpringBoot整合Swagger测试api构建

    @Author:SimpleWu 什么是Swagger? Swagger是什么:THE WORLD'S MOST POPULAR API TOOLING 根据官网的介绍: Swagger Inspec ...

  9. 【FastDFS】SpringBoot整合FastDFS实战,我只看这一篇!!

    写在前面 在<[FastDFS]小伙伴们说在CentOS 8服务器上搭建FastDFS环境总报错?>和<[FastDFS]面试官:如何实现文件的大规模分布式存储?(全程实战)> ...

随机推荐

  1. Spring Boot 2.X(二):集成 MyBatis 数据层开发

    MyBatis 简介 概述 MyBatis 是一款优秀的持久层框架,支持定制化 SQL.存储过程以及高级映射.它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简 ...

  2. TensorFlow2.0(六):Dataset

    .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...

  3. 最简单的JS实现json转csv

    工作久了,总会遇到各种各样的数据处理工作,比如同步数据,初始化一些数据,目前比较流行的交互数据格式就是JSON,可是服务器中得到的JSON数据如果提供给业务人员看的话可能会非常不方便,这时候,转成CS ...

  4. @ConfigurationProperties、@Value、@PropertySource

    @ConfigurationProperties(spring-boot依赖下).@Value(spring-beans依赖下).@PropertySource(spring-context依赖下) ...

  5. [BZOJ4990][Usaco2017 Feb]Why Did the Cow Cross the Road II

    Description Farmer John is continuing to ponder the issue of cows crossing the road through his farm ...

  6. MVC路径无匹配或请求api版本过低时处理

    解决方案:RequestMappingHandlerMapping中重写handleNoMatch方法,springMVC和springboot中配置无区别. 另: 1.可搭配advice处理抛出的异 ...

  7. Linux power supply class(1)_软件架构及API汇整【转】

    1. 前言 power supply class为编写供电设备(power supply,后面简称PSY)的驱动提供了统一的框架,功能包括: 1)抽象PSY设备的共性,向用户空间提供统一的API. 2 ...

  8. Unity3D 通过JSON查询天气

    一.天气查询API 获取天气信息,首先要找到提供天气数据的接口,我使用的是高德地图免费为我们提供的,网址为 https://lbs.amap.com/api/webservice/guide/api/ ...

  9. golang会取代php吗

    看看PHP和Golang如何在开发速度,性能,安全性,可伸缩性等方面展开合作. PHP与Golang比较是一个艰难的比较. PHP最初创建于1994年,已有24年.自那时起,由于PHP的开源格式,易用 ...

  10. SpringBoot学习(一)基础篇

    目录 关于Springboot Springboot优势 快速入门 关于SpringBoot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭 ...