一、swagger 简介
swagger 是一套用于生成、描述和调用 restful api 的规范和工具,主要优势包括:
- 自动生成文档:无需手动编写,通过代码注解自动生成 api 文档。
- 交互式调试:支持在线测试 api 接口,无需依赖 postman 等工具。
- 版本管理:方便 api 版本迭代和维护。
- 团队协作:前后端开发者可基于同一套文档协作,减少沟通成本。
二、环境准备
基础环境
- jdk:17 及以上(本文基于 spring boot 3.x,需兼容 java 17+)
- spring boot 版本:3.5.3(其他 2.6+ 版本可参考,注意版本兼容)
- 开发工具: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)存在一定兼容性问题,需通过后续配置解决(见步骤 3)。
如果不成功可以
2. 配置 swagger 核心类
创建 swaggerconfig
配置类,用于自定义 swagger 文档信息、扫描规则等:
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 // 标识为配置类 @enableswagger2 // 启用 swagger2 public class swaggerconfig implements webmvcconfigurer { /** * 配置 swagger 核心对象 docket */ @bean public docket createrestapi() { return new docket(documentationtype.swagger_2) // 指定 swagger 版本为 2.x .apiinfo(apiinfo()) // 配置 api 文档基本信息 .select() // 配置接口扫描规则:只扫描带有 @apioperation 注解的方法 .apis(requesthandlerselectors.withmethodannotation(apioperation.class)) .paths(pathselectors.any()) // 匹配所有路径 .build() .enable(true); // 是否启用 swagger(生产环境可设为 false 关闭) } /** * 配置 api 文档页面信息(标题、描述、版本等) */ private apiinfo apiinfo() { return new apiinfobuilder() .title("spring boot api 文档") // 文档标题 .description("接口文档详情:包含用户管理、数据查询等接口") // 文档描述 .version("1.0.0") // 接口版本 .contact(new contact("开发者", "https://xxx.com", "xxx@example.com")) // 联系人信息 .license("apache 2.0") // 许可协议 .licenseurl("https://www.apache.org/licenses/license-2.0") // 许可协议链接 .build(); } /** * 配置静态资源映射(解决 swagger ui 页面无法访问问题) */ @override public void addresourcehandlers(resourcehandlerregistry registry) { // 映射 swagger ui 静态资源 registry.addresourcehandler("swagger-ui.html") .addresourcelocations("classpath:/meta-inf/resources/"); // 映射 webjars 静态资源(swagger ui 依赖的前端资源) registry.addresourcehandler("/webjars/**") .addresourcelocations("classpath:/meta-inf/resources/webjars/"); // 映射项目自定义静态资源(如需要) registry.addresourcehandler("/**") .addresourcelocations("classpath:/static/"); } }
3. 解决 spring boot 版本兼容问题
spring boot 2.6+ 及 3.x 版本默认使用 pathpatternparser
作为路径匹配策略,与 swagger2 存在冲突,需手动切换为 antpathmatcher
。
在 application.yml
中添加配置:
spring: mvc: pathmatch: matching-strategy: ant_path_matcher # 切换为 ant 风格路径匹配器
4. 编写 api 接口并添加 swagger 注解
在 controller 中使用 swagger 注解描述接口,生成更详细的文档:
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 = "获取数据库中所有人员信息列表") // 描述方法作用 @requestmapping("/findall") @responsebody public list<person> findall() { return personservice.findall(); } @apioperation(value = "添加人员", notes = "根据传入的人员信息新增一条记录") @requestmapping("/insert") @responsebody public string insert( @apiparam(name = "person", value = "人员实体对象", required = true) // 描述参数 person person) { int result = personservice.insert(person); return result > 0 ? "插入成功" : "插入失败"; } @apioperation(value = "删除人员", notes = "根据 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 注解说明:
@api(tags = "...")
:描述类 / 控制器的作用。@apioperation(value = "...", notes = "...")
:描述方法的作用(value 为简短说明,notes 为详细描述)。@apiparam(...)
:描述方法参数(名称、说明、是否必填、示例值等)。@apimodel(...)
:描述实体类(如person
)。@apimodelproperty(...)
:描述实体类字段(如person
的name
、age
字段)。
5. 访问 swagger ui 文档
启动 spring boot 项目,访问以下地址:http://localhost:8080/swagger-ui.html
成功访问后,将看到如下界面:
- 左侧:接口列表(按 controller 分组)。
- 右侧:接口详情(请求参数、响应示例、测试按钮等)。
可直接在页面上输入参数,点击「try it out」测试接口,无需额外工具。
四、常见问题及解决方案
1. 访问 swagger-ui.html 出现 404 错误
- 原因 1:静态资源映射未配置或错误。
解决:检查swaggerconfig
中的addresourcehandlers
方法,确保路径映射正确。 - 原因 2:spring boot 版本与 swagger2 不兼容。
解决:确认mvc.pathmatch.matching-strategy
已设置为ant_path_matcher
。 - 原因 3:依赖缺失或版本冲突。
解决:检查pom.xml
中springfox-swagger2
和springfox-swagger-ui
版本是否一致(推荐 2.9.2)。
2. 接口未在 swagger 文档中显示
- 原因 1:
docket
配置的扫描规则过滤了接口。
解决:修改apis(requesthandlerselectors.withmethodannotation(apioperation.class))
为apis(requesthandlerselectors.basepackage("com.qcby.springboot.controller"))
(扫描指定包下的所有接口)。 - 原因 2:接口未添加
@apioperation
注解。
解决:在需要显示的方法上添加@apioperation
注解。
3. spring boot 3.x 兼容问题
swagger2(springfox
)对 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构建可视化api文档的完整步骤的详细内容,更多关于springboot swagger2可视化api文档的资料请关注代码网其它相关文章!
发表评论