Swagger自动生成交互API
参考当前Springboot支持的版本,例如3.x使用4.0.0以上的Knife4j
<!--引入knife4j依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>

可以看到它的子依赖有swagger2.3.0的东西,Knife4j做了更符合国人的前端ui显示,同时使用的几乎所有注解都来自于swagger。
但自从Springboot3.x开始仅支持OpenAPI3的规范。对于Knife4j 4.5.0引用的依赖需要自定义版本。
<!--规定引用的所有springdoc-openapi-starter-webmvc-ui子依赖依赖版本都是2.8.9-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
。。。
</dependencies>
同步项目以后,效果:

需要在application.yaml中写如下配置:
# springdoc-openapi项目配置
springdoc:
group-configs: # 下拉菜单的组(如果不写会在菜单栏中全部展示)
- group: '用户管理UserController'
paths-to-match: '/user/**'
- group: '学生管理StudentController'
paths-to-match: '/student/**'
# knife4j的增强配置,默认已经开启,设置enable:true会报错
knife4j:
enable: false
setting:
language: zh_cn
入口:http://localhost:8080/doc.html
完善接口文档用到的注解:
| 关键注解 | 位置 | 例子 |
|---|---|---|
| @Tag | Controller类上 | @Tag(name = "用户管理", description = "用户管理模块") |
| @Operation | 方法上 | @Operation(summary = "根据id查询用户", description = "获取用户信息") |
| @Parameter | 参数前 | @Parameter(description = "用户id", required = true) |
| @Schema | 实体类上和属性上 | @Schema(description = "学生数据传输对象") @Schema(description = "学号", example = "20210001") |
posted on 2026-06-10 21:41 HarryTruman 阅读(4) 评论(0) 收藏 举报
浙公网安备 33010602011771号