SpringBoot中使用Swagger的最全方法詳解
Swagger是什么?
Swagger是一套基于OpenAPI規(guī)范構(gòu)建的開(kāi)源工具,可以幫助我們?cè)O(shè)計(jì)、構(gòu)建、記錄以及使用Rest API。Swagger主要包括了一下三個(gè)部分:
- Swagger Editor: 基于瀏覽器的編輯器,我們可以使用它來(lái)編寫(xiě)我們的OpenAPI文檔。
- Swagger UI: 它會(huì)將我們編寫(xiě)的OpenAPI規(guī)范呈現(xiàn)為交互式的API文檔。后文我們將使用瀏覽器來(lái)查看并且操作我們的Rest API。
- Swagger CodeGen:它可以通過(guò)為OpenAPI規(guī)范定義的任何API生成服務(wù)器存根和客戶端SDK來(lái)簡(jiǎn)化構(gòu)建過(guò)程。
簡(jiǎn)單點(diǎn)來(lái)講就是說(shuō),swagger是一款可以根據(jù)resutful風(fēng)格生成的生成的接口開(kāi)發(fā)文檔,并且支持做測(cè)試的一款中間軟件。
為什么要用Swagger?
后端:
- 不用再手寫(xiě)WiKi接口拼大量的參數(shù),避免手寫(xiě)錯(cuò)誤
- 對(duì)代碼侵入性低,采用全注解的方式,開(kāi)發(fā)簡(jiǎn)單
- 方法參數(shù)名修改、增加、減少參數(shù)都可以直接生效,不用手動(dòng)維護(hù)
- 缺點(diǎn):增加了開(kāi)發(fā)成本,寫(xiě)接口還得再寫(xiě)一套參數(shù)配置
前端:
- 后端只需要定義好接口,會(huì)自動(dòng)生成文檔,接口功能、參數(shù)一目了然
- 聯(lián)調(diào)方便,如果出問(wèn)題,直接測(cè)試接口,實(shí)時(shí)檢查參數(shù)和返回值,就可以快速定位是前端還是后端的問(wèn)題
測(cè)試:
- 對(duì)于某些沒(méi)有前端界面UI的功能,可以用它來(lái)測(cè)試接口
- 操作簡(jiǎn)單,不用了解具體代碼就可以操作
準(zhǔn)備工作
使用的環(huán)境:
- springboot: 2.7.8-SNAPSHOT
- Java:1.8
- swagger:2.9.2
<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>
創(chuàng)建項(xiàng)目

添加依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <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> </dependencies>
編寫(xiě)接口
UserController提供了用戶的增、刪、改、查四個(gè)接口,TestController提供了一個(gè)測(cè)試接口
pojo.user源碼:
package com.example.demo.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @Author 秋名山碼神
* @Date 2023/1/9
* @Description
*/
@ApiModel("用戶實(shí)體類(lèi)")
public class User {
@ApiModelProperty("用戶名")
private String username;
@ApiModelProperty("密碼")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserController源碼:
package com.example.demo.controller;
import com.example.demo.pojo.User;
import org.springframework.web.bind.annotation.*;
/**
* @Author 秋名山碼神
* @Date 2023/1/9
* @Description
*/
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public boolean addUser(User user){
return false;
}
@GetMapping("/find/{id}")
public User findById(@PathVariable("id") int id) {
return new User();
}
@PutMapping("/update")
public boolean update(@RequestBody User user) {
return true;
}
@DeleteMapping("/delete/{id}")
public boolean delete(@PathVariable("id") int id) {
return true;
}
}
SwaggerConfig源碼
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Author 秋名山碼神
* @Date 2023/1/9
* @Description
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
// 配置Swagger的Docket的bean實(shí)例
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
// RequestHandlerSelectors配置掃描接口的方式
.apis(RequestHandlerSelectors.any())
// path過(guò)濾什么路徑
.paths(PathSelectors.any())
.build();
}
@Configuration是告訴Spring Boot需要加載這個(gè)配置類(lèi);@EnableSwagger2是啟用Swagger2.
驗(yàn)證
啟動(dòng)一下項(xiàng)目,然后在瀏覽器中訪問(wèn)http://localhost:8080/swagger-ui.html

到此項(xiàng)目已經(jīng)跑起來(lái)了,我們來(lái)解釋一下,Swagger中的高級(jí)配置**(代碼注釋寫(xiě)的也很清楚)**
高級(jí)配置
文檔注釋
- 通過(guò)在控制器類(lèi)上添加@Api注解,可以給控制器增加描述和標(biāo)簽信息
@Api(tags = "用戶相關(guān)接口",description = "提供用戶相關(guān)的Rest API")
public class UserController {
- 通過(guò)在接口方法上添加@ApiOperation注解來(lái)展開(kāi)對(duì)接口的描述
@ApiOperation("添加用戶操作")
@PostMapping("/add")
public boolean addUser(User user){
return false;
}
- 通過(guò)在實(shí)體類(lèi)上添加@ApiModel和@ApiModelProperty注解來(lái)對(duì)我們的API所涉及到的對(duì)象做描述
@ApiModel("用戶實(shí)體類(lèi)")
public class User {
@ApiModelProperty("用戶名")
private String username;
@ApiModelProperty("密碼")
private String password;
- 文檔信息配置,Swagger還支持設(shè)置一些文檔的版本號(hào)、聯(lián)系人郵箱、網(wǎng)站、版權(quán)、開(kāi)源協(xié)議等等信息,但與上面幾條不同的是這些信息不能通過(guò)注解配置,而是通過(guò)創(chuàng)建一個(gè)ApiInfo對(duì)象,并且使用appInfo()方法來(lái)設(shè)置,我們?cè)赟waggerConfig.java類(lèi)中新增如下內(nèi)容即可:
@Bean
// 配置Swagger的Docket的bean實(shí)例
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
// RequestHandlerSelectors配置掃描接口的方式
.apis(RequestHandlerSelectors.any())
// path過(guò)濾什么路徑
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfo(
"Spring Boot 項(xiàng)目集成 Swagger 實(shí)例文檔",
"歡迎",
"API V1.0",
"Terms of service",
new Contact("名字想好沒(méi)", "csdn", "163.com"),
"Apache", "http://www.apache.org/", Collections.emptyList());
}
接口過(guò)濾
加注解:如果想在文檔中屏蔽掉某個(gè)接口方法,只需要在該接口方法上添加@ApiIgnore即可
在Docket上增加篩選。Docket提供了apis()和paths()兩個(gè)方法來(lái)幫助我們?cè)诓煌?jí)別上過(guò)濾接口:
apis(): 這種方式我們可以通過(guò)指定包名的方式,讓Swagger 只去某些包下掃描。
paths(): 這種方式可以通過(guò)篩選API的 url 來(lái)進(jìn)行過(guò)濾。
自定義響應(yīng)
Docket的globalResponseMessage()方法全局覆蓋HTTP方法的響應(yīng)消息,但是我們首先得通過(guò)Docket的useDefaultResponseMessage()方法告訴Swagger不適用默認(rèn)的HTTP響應(yīng)消息 ,假設(shè)我們需要覆蓋所有GET方法的 500 和 403 錯(cuò)誤的響應(yīng)消息。我們只需要在SwaggerConfig.java 類(lèi)種的Docket Bean下添加如下內(nèi)容:
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET, newArrayList(
new ResponseMessageBuilder()
.code(500)
.message("服務(wù)器發(fā)生異常")
.responseModel(new ModelRef("Error"))
.build(),
new ResponseMessageBuilder()
.code(403)
.message("資源不可用")
.build()
));
SwaggerUI的使用
接口調(diào)用


遇到的問(wèn)題:
啟動(dòng)項(xiàng)目報(bào)空指針異常

添加這個(gè)代碼:spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
總結(jié)
到此這篇關(guān)于SpringBoot中使用Swagger的文章就介紹到這了,更多相關(guān)SpringBoot使用Swagger內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot集成swagger、knife4j及常用注解的使用
- SpringBoot項(xiàng)目中使用Swagger2及注解解釋的詳細(xì)教程
- SpringBoot使用Swagger范例講解
- 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中繼承關(guān)系類(lèi)加載順序問(wèn)題
這篇文章主要介紹了詳解java中繼承關(guān)系類(lèi)加載順序問(wèn)題的相關(guān)資料,需要的朋友可以參考下2017-06-06
SpringBoot深入分析webmvc和webflux的區(qū)別
這篇文章主要介紹了SpringBoot深入分析webmvc和webflux的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-02-02
springboot基于docsify?實(shí)現(xiàn)隨身文檔
這篇文章主要介紹了springboot基于docsify實(shí)現(xiàn)隨身文檔的相關(guān)資料,需要的朋友可以參考下2022-09-09
Java中快速排序優(yōu)化技巧之隨機(jī)取樣、三數(shù)取中和插入排序
快速排序是一種常用的基于比較的排序算法,下面這篇文章主要給大家介紹了關(guān)于Java中快速排序優(yōu)化技巧之隨機(jī)取樣、三數(shù)取中和插入排序的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09
MapStruct升級(jí)遇到的問(wèn)題及解決方案
MapStruct是一個(gè)用于生成類(lèi)型安全,本文來(lái)介紹一下MapStruct升級(jí)遇到的問(wèn)題及解決方案,具有一定的參考價(jià)值,感興趣的可以了解一下2024-12-12

