SpringBoot集成Swagger2構(gòu)建可視化API文檔的完整步驟
一、Swagger 簡(jiǎn)介
Swagger 是一套用于生成、描述和調(diào)用 RESTful API 的規(guī)范和工具,主要優(yōu)勢(shì)包括:
- 自動(dòng)生成文檔:無(wú)需手動(dòng)編寫,通過代碼注解自動(dòng)生成 API 文檔。
- 交互式調(diào)試:支持在線測(cè)試 API 接口,無(wú)需依賴 Postman 等工具。
- 版本管理:方便 API 版本迭代和維護(hù)。
- 團(tuán)隊(duì)協(xié)作:前后端開發(fā)者可基于同一套文檔協(xié)作,減少溝通成本。
二、環(huán)境準(zhǔn)備
基礎(chǔ)環(huán)境
- JDK:17 及以上(本文基于 Spring Boot 3.x,需兼容 Java 17+)
- Spring Boot 版本:3.5.3(其他 2.6+ 版本可參考,注意版本兼容)
- 開發(fā)工具:IntelliJ IDEA
- 依賴管理:Maven
三、集成步驟
1. 添加 Swagger2 依賴
在 pom.xml 中添加 Swagger2 核心依賴(springfox-swagger2 和 springfox-swagger-ui):
<!-- Swagger2 核心依賴 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger2 可視化界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>注意:Spring Boot 2.6+ 及 3.x 版本與 Swagger2(2.9.2)存在一定兼容性問題,需通過后續(xù)配置解決(見步驟 3)。
如果不成功可以

2. 配置 Swagger 核心類
創(chuàng)建 SwaggerConfig 配置類,用于自定義 Swagger 文檔信息、掃描規(guī)則等:
package com.qcby.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;
@Configuration // 標(biāo)識(shí)為配置類
@EnableSwagger2 // 啟用 Swagger2
public class SwaggerConfig implements WebMvcConfigurer {
/**
* 配置 Swagger 核心對(duì)象 Docket
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) // 指定 Swagger 版本為 2.x
.apiInfo(apiInfo()) // 配置 API 文檔基本信息
.select()
// 配置接口掃描規(guī)則:只掃描帶有 @ApiOperation 注解的方法
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any()) // 匹配所有路徑
.build()
.enable(true); // 是否啟用 Swagger(生產(chǎn)環(huán)境可設(shè)為 false 關(guān)閉)
}
/**
* 配置 API 文檔頁(yè)面信息(標(biāo)題、描述、版本等)
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot API 文檔") // 文檔標(biāo)題
.description("接口文檔詳情:包含用戶管理、數(shù)據(jù)查詢等接口") // 文檔描述
.version("1.0.0") // 接口版本
.contact(new Contact("開發(fā)者", "https://xxx.com", "xxx@example.com")) // 聯(lián)系人信息
.license("Apache 2.0") // 許可協(xié)議
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") // 許可協(xié)議鏈接
.build();
}
/**
* 配置靜態(tài)資源映射(解決 Swagger UI 頁(yè)面無(wú)法訪問問題)
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 映射 Swagger UI 靜態(tài)資源
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// 映射 webjars 靜態(tài)資源(Swagger UI 依賴的前端資源)
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
// 映射項(xiàng)目自定義靜態(tài)資源(如需要)
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
}
}3. 解決 Spring Boot 版本兼容問題
Spring Boot 2.6+ 及 3.x 版本默認(rèn)使用 PathPatternParser 作為路徑匹配策略,與 Swagger2 存在沖突,需手動(dòng)切換為 AntPathMatcher。
在 application.yml 中添加配置:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher # 切換為 Ant 風(fēng)格路徑匹配器4. 編寫 API 接口并添加 Swagger 注解
在 Controller 中使用 Swagger 注解描述接口,生成更詳細(xì)的文檔:
package com.qcby.springboot.controller;
import com.qcby.springboot.entity.Person;
import com.qcby.springboot.service.PersonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Api(tags = "人員管理接口") // 描述類的作用
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@ApiOperation(value = "查詢所有人員", notes = "獲取數(shù)據(jù)庫(kù)中所有人員信息列表") // 描述方法作用
@RequestMapping("/findAll")
@ResponseBody
public List<Person> findAll() {
return personService.findAll();
}
@ApiOperation(value = "添加人員", notes = "根據(jù)傳入的人員信息新增一條記錄")
@RequestMapping("/insert")
@ResponseBody
public String insert(
@ApiParam(name = "person", value = "人員實(shí)體對(duì)象", required = true) // 描述參數(shù)
Person person) {
int result = personService.insert(person);
return result > 0 ? "插入成功" : "插入失敗";
}
@ApiOperation(value = "刪除人員", notes = "根據(jù) ID 刪除指定人員記錄")
@RequestMapping("/delete")
@ResponseBody
public String delete(
@ApiParam(name = "id", value = "人員 ID", required = true, example = "1")
Integer id) {
int result = personService.delete(id);
return result > 0 ? "刪除成功" : "刪除失敗";
}
}常用 Swagger 注解說(shuō)明:
@Api(tags = "..."):描述類 / 控制器的作用。@ApiOperation(value = "...", notes = "..."):描述方法的作用(value 為簡(jiǎn)短說(shuō)明,notes 為詳細(xì)描述)。@ApiParam(...):描述方法參數(shù)(名稱、說(shuō)明、是否必填、示例值等)。@ApiModel(...):描述實(shí)體類(如Person)。@ApiModelProperty(...):描述實(shí)體類字段(如Person的name、age字段)。



5. 訪問 Swagger UI 文檔
啟動(dòng) Spring Boot 項(xiàng)目,訪問以下地址:http://localhost:8080/swagger-ui.html
成功訪問后,將看到如下界面:
- 左側(cè):接口列表(按 Controller 分組)。
- 右側(cè):接口詳情(請(qǐng)求參數(shù)、響應(yīng)示例、測(cè)試按鈕等)。
可直接在頁(yè)面上輸入?yún)?shù),點(diǎn)擊「Try it out」測(cè)試接口,無(wú)需額外工具。







四、常見問題及解決方案
1. 訪問 swagger-ui.html 出現(xiàn) 404 錯(cuò)誤
- 原因 1:靜態(tài)資源映射未配置或錯(cuò)誤。
解決:檢查SwaggerConfig中的addResourceHandlers方法,確保路徑映射正確。 - 原因 2:Spring Boot 版本與 Swagger2 不兼容。
解決:確認(rèn)mvc.pathmatch.matching-strategy已設(shè)置為ant_path_matcher。 - 原因 3:依賴缺失或版本沖突。
解決:檢查pom.xml中springfox-swagger2和springfox-swagger-ui版本是否一致(推薦 2.9.2)。
2. 接口未在 Swagger 文檔中顯示
- 原因 1:
Docket配置的掃描規(guī)則過濾了接口。
解決:修改apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))為apis(RequestHandlerSelectors.basePackage("com.qcby.springboot.controller"))(掃描指定包下的所有接口)。 - 原因 2:接口未添加
@ApiOperation注解。
解決:在需要顯示的方法上添加@ApiOperation注解。
3. Spring Boot 3.x 兼容問題
Swagger2(springfox)對(duì) Spring Boot 3.x 支持有限,推薦使用 OpenAPI 3.0 替代方案(springdoc-openapi):
<!-- 替代 Swagger2 的 OpenAPI 3.0 依賴 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.2.0</version>
</dependency>以上就是SpringBoot集合Swagger2構(gòu)建可視化API文檔的完整步驟的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Swagger2可視化API文檔的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之食品溯源系統(tǒng)的實(shí)現(xiàn)
這是一個(gè)使用了java+Springboot+Maven+mybatis+Vue+mysql+wd開發(fā)的食品溯源系統(tǒng),是一個(gè)畢業(yè)設(shè)計(jì)的實(shí)戰(zhàn)練習(xí),具有食品溯源該有的所有功能,感興趣的朋友快來(lái)看看吧2022-01-01
Java框架學(xué)習(xí)Struts2復(fù)選框?qū)嵗a
這篇文章主要介紹了Java框架學(xué)習(xí)Struts2復(fù)選框?qū)嵗a,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
Java中的CGLIB動(dòng)態(tài)代理的使用及原理詳解
這篇文章主要介紹了Java中的CGLIB動(dòng)態(tài)代理的使用及原理詳解,CGLIB是一個(gè)功能強(qiáng)大,高性能的代碼生成包,它為沒有實(shí)現(xiàn)接口的類提供代理,為JDK的動(dòng)態(tài)代理提供了很好的補(bǔ)充,需要的朋友可以參考下2023-09-09
java 使用idea將工程打成jar并創(chuàng)建成exe文件類型執(zhí)行的方法詳解
這篇文章主要介紹了java 使用idea將工程打成jar并創(chuàng)建成exe文件類型執(zhí)行,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-09-09
Mybatis之映射實(shí)體類中不區(qū)分大小寫的解決
這篇文章主要介紹了Mybatis之映射實(shí)體類中不區(qū)分大小寫的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
超詳細(xì)介紹idea中java程序打jar包的兩種方式
這篇文章主要介紹了超詳細(xì)介紹idea中java程序打jar包的兩種方式一種是可直接執(zhí)行的runnable jar文件,另一種是包含多個(gè)主類,運(yùn)行時(shí)需要指定主類全類名的jar包,感興趣的可以了解一下2020-07-07
Spring Boot 將yyyy-MM-dd格式的文本字符串直接轉(zhuǎn)換為L(zhǎng)ocalDateTime出現(xiàn)的問題
這篇文章主要介紹了Spring Boot 將yyyy-MM-dd格式的文本字符串直接轉(zhuǎn)換為L(zhǎng)ocalDateTime出現(xiàn)的問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

