SpringBoot中使用Swagger的最全方法詳解
Swagger是什么?
Swagger是一套基于OpenAPI規(guī)范構(gòu)建的開源工具,可以幫助我們設(shè)計、構(gòu)建、記錄以及使用Rest API。Swagger主要包括了一下三個部分:
- Swagger Editor: 基于瀏覽器的編輯器,我們可以使用它來編寫我們的OpenAPI文檔。
- Swagger UI: 它會將我們編寫的OpenAPI規(guī)范呈現(xiàn)為交互式的API文檔。后文我們將使用瀏覽器來查看并且操作我們的Rest API。
- Swagger CodeGen:它可以通過為OpenAPI規(guī)范定義的任何API生成服務(wù)器存根和客戶端SDK來簡化構(gòu)建過程。
簡單點來講就是說,swagger是一款可以根據(jù)resutful風(fēng)格生成的生成的接口開發(fā)文檔,并且支持做測試的一款中間軟件。
為什么要用Swagger?
后端:
- 不用再手寫WiKi接口拼大量的參數(shù),避免手寫錯誤
- 對代碼侵入性低,采用全注解的方式,開發(fā)簡單
- 方法參數(shù)名修改、增加、減少參數(shù)都可以直接生效,不用手動維護(hù)
- 缺點:增加了開發(fā)成本,寫接口還得再寫一套參數(shù)配置
前端:
- 后端只需要定義好接口,會自動生成文檔,接口功能、參數(shù)一目了然
- 聯(lián)調(diào)方便,如果出問題,直接測試接口,實時檢查參數(shù)和返回值,就可以快速定位是前端還是后端的問題
測試:
- 對于某些沒有前端界面UI的功能,可以用它來測試接口
- 操作簡單,不用了解具體代碼就可以操作
準(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)建項目
添加依賴
<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>
編寫接口
UserController提供了用戶的增、刪、改、查四個接口,TestController提供了一個測試接口
pojo.user源碼:
package com.example.demo.pojo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @Author 秋名山碼神 * @Date 2023/1/9 * @Description */ @ApiModel("用戶實體類") 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實例 public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .select() // RequestHandlerSelectors配置掃描接口的方式 .apis(RequestHandlerSelectors.any()) // path過濾什么路徑 .paths(PathSelectors.any()) .build(); }
@Configuration是告訴Spring Boot需要加載這個配置類;@EnableSwagger2是啟用Swagger2.
驗證
啟動一下項目,然后在瀏覽器中訪問http://localhost:8080/swagger-ui.html
到此項目已經(jīng)跑起來了,我們來解釋一下,Swagger中的高級配置**(代碼注釋寫的也很清楚)**
高級配置
文檔注釋
- 通過在控制器類上添加@Api注解,可以給控制器增加描述和標(biāo)簽信息
@Api(tags = "用戶相關(guān)接口",description = "提供用戶相關(guān)的Rest API") public class UserController {
- 通過在接口方法上添加@ApiOperation注解來展開對接口的描述
@ApiOperation("添加用戶操作") @PostMapping("/add") public boolean addUser(User user){ return false; }
- 通過在實體類上添加@ApiModel和@ApiModelProperty注解來對我們的API所涉及到的對象做描述
@ApiModel("用戶實體類") public class User { @ApiModelProperty("用戶名") private String username; @ApiModelProperty("密碼") private String password;
- 文檔信息配置,Swagger還支持設(shè)置一些文檔的版本號、聯(lián)系人郵箱、網(wǎng)站、版權(quán)、開源協(xié)議等等信息,但與上面幾條不同的是這些信息不能通過注解配置,而是通過創(chuàng)建一個ApiInfo對象,并且使用appInfo()方法來設(shè)置,我們在SwaggerConfig.java類中新增如下內(nèi)容即可:
@Bean // 配置Swagger的Docket的bean實例 public Docket api(){ return new Docket(DocumentationType.SWAGGER_2) .select() // RequestHandlerSelectors配置掃描接口的方式 .apis(RequestHandlerSelectors.any()) // path過濾什么路徑 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfo( "Spring Boot 項目集成 Swagger 實例文檔", "歡迎", "API V1.0", "Terms of service", new Contact("名字想好沒", "csdn", "163.com"), "Apache", "http://www.apache.org/", Collections.emptyList()); }
接口過濾
加注解:如果想在文檔中屏蔽掉某個接口方法,只需要在該接口方法上添加@ApiIgnore即可
在Docket上增加篩選。Docket提供了apis()和paths()兩個方法來幫助我們在不同級別上過濾接口:
apis(): 這種方式我們可以通過指定包名的方式,讓Swagger 只去某些包下掃描。
paths(): 這種方式可以通過篩選API的 url 來進(jìn)行過濾。
自定義響應(yīng)
Docket的globalResponseMessage()方法全局覆蓋HTTP方法的響應(yīng)消息,但是我們首先得通過Docket的useDefaultResponseMessage()方法告訴Swagger不適用默認(rèn)的HTTP響應(yīng)消息 ,假設(shè)我們需要覆蓋所有GET方法的 500 和 403 錯誤的響應(yīng)消息。我們只需要在SwaggerConfig.java 類種的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)用
遇到的問題:
啟動項目報空指針異常
添加這個代碼:spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
總結(jié)
到此這篇關(guān)于SpringBoot中使用Swagger的文章就介紹到這了,更多相關(guān)SpringBoot使用Swagger內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot集成swagger、knife4j及常用注解的使用
- SpringBoot項目中使用Swagger2及注解解釋的詳細(xì)教程
- SpringBoot使用Swagger范例講解
- SpringBoot2.6.x升級后循環(huán)依賴及Swagger無法使用問題
- springboot使用swagger-ui 2.10.5 有關(guān)版本更新帶來的問題小結(jié)
- SpringBoot如何優(yōu)雅地使用Swagger2
- SpringBoot整合Swagger和Actuator的使用教程詳解
- 詳解如何在SpringBoot里使用SwaggerUI
- SpringBoot3使用Swagger3的示例詳解
相關(guān)文章
SpringBoot深入分析webmvc和webflux的區(qū)別
這篇文章主要介紹了SpringBoot深入分析webmvc和webflux的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02springboot基于docsify?實現(xiàn)隨身文檔
這篇文章主要介紹了springboot基于docsify實現(xiàn)隨身文檔的相關(guān)資料,需要的朋友可以參考下2022-09-09Java中快速排序優(yōu)化技巧之隨機(jī)取樣、三數(shù)取中和插入排序
快速排序是一種常用的基于比較的排序算法,下面這篇文章主要給大家介紹了關(guān)于Java中快速排序優(yōu)化技巧之隨機(jī)取樣、三數(shù)取中和插入排序的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09