SpringBoot使用Swagger范例講解
1. Swagger 介紹
在一個(gè)項(xiàng)目開(kāi)發(fā)過(guò)程中,當(dāng)前端開(kāi)發(fā)人員根據(jù)后端開(kāi)發(fā)人員給出的 API 接口文檔進(jìn)行接口聯(lián)調(diào)對(duì)接時(shí),可能會(huì)出現(xiàn)這樣的矛盾:前端開(kāi)發(fā)人員抱怨后端開(kāi)發(fā)人員給出的 API 接口文檔和實(shí)際的情況有所出入,而后端開(kāi)發(fā)人員由于繁重的開(kāi)發(fā)任務(wù)已經(jīng)身心俱疲,想到自己還要負(fù)責(zé)維護(hù)接口文檔的任務(wù)更是不堪重負(fù)。
這時(shí)就需要一個(gè)解決方案,希望它能夠在后端開(kāi)發(fā)人員進(jìn)行接口開(kāi)發(fā)時(shí),能夠幫助后端工程師自動(dòng)生成相應(yīng)的接口文檔,當(dāng)接口有變化時(shí),也能夠?qū)ξ臋n進(jìn)行及時(shí)更新,這樣前端工程師在進(jìn)行接口聯(lián)調(diào)時(shí),不會(huì)再出現(xiàn)發(fā)現(xiàn)文檔和實(shí)際情況不一致的情況。
幸運(yùn)的是,偉大的開(kāi)源社區(qū)就給出了這樣的一套解決方案,稱為 Swagger,正如它的中譯一樣,讓后端工程師能夠大搖大擺地走,以后再面對(duì)前端工程師時(shí)神奇十足哈哈!
Swagger 是一個(gè)規(guī)范和完整的框架,它用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù),避免手動(dòng)維護(hù) API 文檔的帶來(lái)的麻煩。
后端工程師只需要按照它的規(guī)范去定義接口及接口相關(guān)的信息,再通過(guò) Swagger 衍生出來(lái)的一系列項(xiàng)目和工具,就可以做到生成各種格式的接口文檔,生成多種語(yǔ)言的客戶端和服務(wù)端的代碼,以及在線接口調(diào)試頁(yè)面等等。
這樣,如果按照新的開(kāi)發(fā)模式,在開(kāi)發(fā)新版本或者迭代版本的時(shí)候,只需要更新 Swagger 描述文件,就可以自動(dòng)生成接口文檔和客戶端服務(wù)端代碼,做到調(diào)用端代碼、服務(wù)端代碼以及接口文檔的一致性。
2. 使用Swagger接口文檔框架
為了簡(jiǎn)化 Swagger 的使用,Spring 框架對(duì) Swagger 進(jìn)行了整合,建立了 Spring-Swagger 項(xiàng)目,之后又更新作 Springfox. 通過(guò)在項(xiàng)目中引入 Springfox,可以掃描相關(guān)的代碼,生成描述文件以及與代碼一致的接口文檔和客戶端代碼。
引入 Springfox 的 maven 坐標(biāo)如下
<dependency>
<!--swagger 文檔的 UI 組件-->
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
Swagger 常用的注解及對(duì)應(yīng)的描述如下表所示:
| 注解 | 描述 |
|---|---|
| @Api | 用在請(qǐng)求的類上,例如 @Controller,表示對(duì)類的說(shuō)明 |
| @ApiModel | 用在類上,通常是實(shí)體類,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息 |
| @ApiModelProperty | 用在屬性上,描述響應(yīng)類的屬性 |
| @ApiOperation | 用在請(qǐng)求的方法上,說(shuō)明方法的用途、作用 |
| @ApiImplicitParams | 用在請(qǐng)求的方法上,表示一組參數(shù)說(shuō)明 |
| @ApiImplicitParam | 用在 @ApiImplicitParams 注解中,指定一個(gè)請(qǐng)求參數(shù)的各個(gè)方面 |
下面就開(kāi)始著手在 SpringBoot 項(xiàng)目中使用 Swagger 文檔接口。
第一步,創(chuàng)建一個(gè)名為 swagger_demo 的 maven 工程,工程的 pom.xml 文件內(nèi)容如下
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hzz</groupId>
<artifactId>swagger_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger 文檔的 UI 組件-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>第二步,在 resources 目錄下創(chuàng)建 application.yml 文件
server:
port: 9000 #指定服務(wù)端口號(hào)
第三步,創(chuàng)建實(shí)體類 User 和 Menu
User 類
package com.hzz.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "用戶實(shí)體")
public class User {
@ApiModelProperty(value = "主鍵")
private int id;
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "年齡")
private int age;
@ApiModelProperty(value = "地址")
private String address;
}Menu 類
package com.hzz.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "菜單實(shí)體")
public class Menu {
@ApiModelProperty(value = "主鍵")
private int id;
@ApiModelProperty(value = "菜單名稱")
private String name;
}第四步,創(chuàng)建 UserController 和 MenuController
UserController 類
package com.hzz.controller.user;
import com.hzz.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/user")
@Api(tags = "用戶控制器")
public class UserController {
@GetMapping("/getUsers")
@ApiOperation(value = "查詢所有用戶", notes = "查詢所有用戶信息")
public List<User> getAllUsers() {
User user = new User();
user.setId(100);
user.setName("hzz");
user.setAge(20);
user.setAddress("hz");
List<User> list = new ArrayList<>();
list.add(user);
return list;
}
@PostMapping("/save")
@ApiOperation(value = "新增用戶", notes = "新增用戶信息")
public String save(@RequestBody User user) {
return "OK";
}
@PutMapping("/update")
@ApiOperation(value = "修改用戶", notes = "修改用戶信息")
public String update(@RequestBody User user) {
return "OK";
}
@DeleteMapping("/delete")
@ApiOperation(value = "刪除用戶", notes = "刪除用戶信息")
public String delete(int id) {
return "OK";
}
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "頁(yè)碼",
required = true, type = "Integer"),
@ApiImplicitParam(name = "pageSize", value = "每頁(yè)條數(shù)",
required = true, type = "Integer"),
})
@ApiOperation(value = "分頁(yè)查詢用戶信息")
@GetMapping(value = "page/{pageNum}/{pageSize}")
public String findByPage(@PathVariable Integer pageNum,
@PathVariable Integer pageSize) {
return "OK";
}
}MenuController 類
package com.hzz.controller.menu;
import com.hzz.entity.Menu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/menu")
@Api(tags = "菜單控制器")
public class MenuController {
@GetMapping("/getMenus")
@ApiOperation(value = "查詢所有菜單", notes = "查詢所有菜單信息")
public List<Menu> getMenus() {
Menu menu = new Menu();
menu.setId(100);
menu.setName("hzz");
List<Menu> list = new ArrayList<>();
list.add(menu);
return list;
}
@PostMapping("/save")
@ApiOperation(value = "新增菜單", notes = "新增菜單信息")
public String save(@RequestBody Menu menu) {
return "OK";
}
@PutMapping("/update")
@ApiOperation(value = "修改菜單", notes = "修改菜單信息")
public String update(@RequestBody Menu menu) {
return "OK";
}
@DeleteMapping("/delete")
@ApiOperation(value = "刪除菜單", notes = "刪除菜單信息")
public String delete(int id){
return "OK";
}
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "頁(yè)碼",
required = true, type = "Integer"),
@ApiImplicitParam(name = "pageSize", value = "每頁(yè)條數(shù)",
required = true, type = "Integer"),
})
@ApiOperation(value = "分頁(yè)查詢菜單信息")
@GetMapping(value = "page/{pageNum}/{pageSize}")
public String findByPage(@PathVariable Integer pageNum,
@PathVariable Integer pageSize) {
return "OK";
}
}第五步,創(chuàng)建 SwaggerAutoConfiguration 配置類
package com.hzz.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
/**
* 自動(dòng)配置類
*/
@Configuration
@EnableSwagger2 //啟動(dòng)swagger
public class SwaggerAutoConfiguration {
@Bean
public Docket createRestApi1() {
//docket 用于封裝接口文檔相關(guān)信息
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.apiInfo(apiInfo()).groupName("用戶接口組")
.select()
//為當(dāng)前包路徑
.apis(RequestHandlerSelectors.basePackage("com.hzz.controller.user"))
.build();
return docket;
}
@Bean
public Docket createRestApi2() {
//docket 用于封裝接口文檔相關(guān)信息
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).groupName("菜單接口組")
.select()
//為當(dāng)前包路徑
.apis(RequestHandlerSelectors.basePackage("com.hzz.controller.menu"))
.build();
return docket;
}
//構(gòu)建 API 文檔的詳細(xì)信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API接口文檔") //頁(yè)面標(biāo)題
//聯(lián)系人
.contact(new Contact("華仔仔coding", null,null)) //url和email沒(méi)有則填充null即可
.version("1.0") //版本號(hào)
.description("API 描述") //描述
.build();
}
}第六步,創(chuàng)建啟動(dòng)類
package com.hzz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}第七步,啟動(dòng)項(xiàng)目,訪問(wèn)地址 http://localhost:9000/swagger-ui.html,swagger 接口文檔可視化界面如下

此外,還可以在文檔中進(jìn)行測(cè)試,可以點(diǎn)擊某個(gè)請(qǐng)求,例如測(cè)試上圖中的 DELETE 請(qǐng)求,點(diǎn)擊 Try it out 進(jìn)行測(cè)試接口

然后,輸入請(qǐng)求的參數(shù),點(diǎn)擊 Execute 執(zhí)行,便可以在 Server response 下方看到響應(yīng)結(jié)果

當(dāng)然,還可以測(cè)試其他的接口,觀察響應(yīng)數(shù)據(jù),為了使得篇幅不那么冗長(zhǎng),這里就不再演示了嗎,以上便是在 SpringBoot 項(xiàng)目中使用 Swagger 接口文檔演示的整個(gè)過(guò)程。
到此這篇關(guān)于SpringBoot使用Swagger范例講解的文章就介紹到這了,更多相關(guān)SpringBoot Swagger內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot集成swagger、knife4j及常用注解的使用
- SpringBoot中使用Swagger的最全方法詳解
- SpringBoot項(xiàng)目中使用Swagger2及注解解釋的詳細(xì)教程
- SpringBoot2.6.x升級(jí)后循環(huán)依賴及Swagger無(wú)法使用問(wèn)題
- springboot使用swagger-ui 2.10.5 有關(guān)版本更新帶來(lái)的問(wèn)題小結(jié)
- SpringBoot如何優(yōu)雅地使用Swagger2
- SpringBoot整合Swagger和Actuator的使用教程詳解
- 詳解如何在SpringBoot里使用SwaggerUI
- SpringBoot3使用Swagger3的示例詳解
相關(guān)文章
一文搞懂Java中對(duì)象池的實(shí)現(xiàn)
池化并不是什么新鮮的技術(shù),它更像一種軟件設(shè)計(jì)模式,主要功能是緩存一組已經(jīng)初始化的對(duì)象,以供隨時(shí)可以使用。本文將為大家詳細(xì)講講Java中對(duì)象池的實(shí)現(xiàn),需要的可以參考一下2022-07-07
利用Kotlin + Spring Boot實(shí)現(xiàn)后端開(kāi)發(fā)
這篇文章主要給大家介紹了關(guān)于利用Kotlin + Spring Boot實(shí)現(xiàn)后端開(kāi)發(fā)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
如何利用 Either 和 Option 進(jìn)行函數(shù)式錯(cuò)誤處理
這篇文章主要介紹了如何利用 Either 和 Option 進(jìn)行函數(shù)式錯(cuò)誤處理。在 Java 中,錯(cuò)誤的處理在傳統(tǒng)上由異常以及創(chuàng)建和傳播異常的語(yǔ)言支持進(jìn)行。但是,如果不存在結(jié)構(gòu)化異常處理又如何呢?,需要的朋友可以參考下2019-06-06
JavaCV攝像頭實(shí)戰(zhàn)之實(shí)現(xiàn)口罩檢測(cè)
這篇文章主要介紹了利用JavaCV實(shí)現(xiàn)口罩檢測(cè),功能是檢測(cè)攝像頭內(nèi)的人是否帶了口罩,把檢測(cè)結(jié)果實(shí)時(shí)標(biāo)注在預(yù)覽窗口。感興趣的可以試一試2022-01-01
MyBatis中批量插入和批量更新的實(shí)現(xiàn)方法詳解
這篇文章主要介紹了MyBatis中批量插入和批量更新的實(shí)現(xiàn)方法,在日常開(kāi)發(fā)中有時(shí)候需要從A數(shù)據(jù)庫(kù)提取大量數(shù)據(jù)同步到B系統(tǒng),這種情況自然是需要批量操作才行,感興趣想要詳細(xì)了解可以參考下文2023-05-05
SpringBoot2入門自動(dòng)配置原理及源碼分析
這篇文章主要為大家介紹了SpringBoot2入門自動(dòng)配置原理及源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
使用Java實(shí)現(xiàn)簡(jiǎn)單串口通信
這篇文章主要介紹了使用Java實(shí)現(xiàn)簡(jiǎn)單串口通信,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
java 根據(jù)坐標(biāo)截取圖片實(shí)例代碼
這篇文章主要介紹了java 根據(jù)坐標(biāo)截取圖片實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03

