springdoc 是基于 spring boot 的现代化 api 文档生成工具,通过自动化扫描代码和注解,生成符合 openapi 3.0+ 规范 的交互式文档,并集成 swagger ui 提供可视化测试界面。以下是其核心详解:
核心特性与优势
开箱即用
仅需添加依赖,无需复杂配置即可自动生成文档,支持 spring webmvc、webflux、spring security 及 jakarta ee。
注解驱动
使用 jsr-303 规范注解(如
@tag
、@operation
)替代 springfox 专属注解,降低学习成本。动态兼容性
完美适配 spring boot 2.6+ 及 3.x(含 jdk 17+),解决 springfox 因停维护导致的不兼容问题。
多格式输出
支持 json/yaml/html 格式文档,并提供分组功能,可按模块划分接口(如公开 api 与内部 api)。
集成与配置
依赖引入(spring boot 3.x)
<dependency> <groupid>org.springdoc</groupid> <artifactid>springdoc-openapi-starter-webmvc-ui</artifactid> <version>2.5.0</version> <!-- 官方稳定版,兼容 spring boot 3.3.x:cite[2]:cite[8] --> </dependency>
基础配置(application.yml)
springdoc: swagger-ui: # 开启 swagger-ui 文档展示 enabled: true # ui访问路径 path: /swagger-ui.html # 标签排序方式 tags-sorter: alpha # 操作排序方式 operations-sorter: alpha # 保持认证状态 persistauthorization: true # 禁用示例接口 disable-swagger-default-url: true api-docs: # 开启 openapi 展示 enabled: true # openapi json路径 path: /v3/api-docs default-consumes-media-type: application/json default-produces-media-type: application/json cache: # 关闭文档缓存 disabled: false # 显示actuator端点 show-actuator: false # 推荐保持默认,显示结构化参数 # default-flat-param-object: true # 允许在文档中展示 spring mvc 的 modelandview 返回类型 model-and-view-allowed: true # 推荐关闭以确保文档精确性 override-with-generic-response: false
全局信息配置类(可选)
@configuration @openapidefinition( info = @info(title = "项目api文档", version = "1.0", description = "springboot接口文档") ) public class springdocconfig { // 无需额外代码 }
注解使用
常用注解
场景 | springdoc 注解 | 示例 |
---|---|---|
控制器描述 | @tag(name="模块", description="") | @tag(name="用户管理", description="用户crud") |
接口方法描述 | @operation(summary="", description="") | @operation(summary="创建用户", description="需管理员权限") |
参数描述 | @parameter(description="") | @parameter(description="用户id", required=true) |
模型属性描述 | @schema(description="") | public class user { @schema(description="用户名") private string name; }l |
解析对象属性为查询参数 | @parameterobject | public bizresponse getuserpage(@parameterobject userpageform form) {} |
提示:
- @hidden 可隐藏接口或参数;
- 支持 spring security 的 @preauthorize 注解,自动在文档中标记权限需求。
控制层注解使用示例
@restcontroller @requestmapping("/api/users") @tag(name = "用户管理", description = "用户相关操作api") public class usercontroller{ @operation(summary = "获取用户信息", description = "通过用户id获取用户信息") @parameters({ @parameter(in = parameterin.path, name = "id", description = "用户uid", required = true) }) @apiresponse(responsecode = "404", description = "user not found") @getmapping("/{id}") public responseentity<user> getuserbyid(@pathvariable long id){ // 实现代码 return new responseentity(new user(10001,"feng","admin"), httpstatuscode.valueof(200)); } @operation(summary = "获取用户列表-分页") @getmapping("/userpage.do") public bizresponse getuserpage(@parameterobject userpageform form) { return bizresponse.ok(userserver.getuserpage(form)); } @operation(summary = "文件上传") @postmapping(name = "/upload", consumes = mediatype.multipart_form_data_value) public bizresponse<fileinfovo> fileupload( @parameter(description = "文件", content = @content(mediatype = mediatype.multipart_form_data_value, schema = @schema(type = "string", format = "binary"))) @requestparam multipartfile file) { fileinfo fileinfo = filestorageservice.of(file).setpath(uploadfilepath).upload(); return bizresponse.ok(fileinfo); } }
模型注解使用示例
import io.swagger.v3.oas.annotations.media.schema; import io.swagger.v3.oas.annotations.media.schema.requiredmode; import jakarta.validation.constraints.email; import jakarta.validation.constraints.size; @data public clas suser{ @schema(description = "用户id", example = "1001") private integer id; @schema(description = "用户名", example = "john_doe", requiredmode = requiredmode.required) @size(min = 3, max = 20, message = "用户名长度必须在3到20个字符之间") private string username; @schema(description = "用户角色", allowablevalues = {"admin", "user", "guest"}) private string role; @schema(description = "邮箱", example = "john_doe@mail.com") @email private string email; @schema(description = "最近登录时间", example = "2025-07-15 12:25:32", type = "string") private date lastlogintime; @schema(description = "出生年月日", example = "2025-07-15", type = "string") @jsonformat(pattern = "yyyy-mm-dd", timezone = "gmt+8") private date birthdate; }
文件上传注解使用示例
文件上传必须声明以下配置,否则 springdoc 无法识别为文件类型,文件参数不会显示为文件上传控件
@postmapping
必须配置consumes = mediatype.multipart_form_data_value
multipartfile
参数必须明确声明format = "binary"
单文件上传
@postmapping(value = "/upload", consumes = mediatype.multipart_form_data_value) @operation(summary = "上传文件") public responseentity<string> uploadfile( @parameter( description = "文件参数", required = true, content = @content( // 关键:嵌套content注解 mediatype = mediatype.application_octet_stream_value, schema = @schema(type = "string", format = "binary") // 明确格式 ) ) @requestparam("file") multipartfile file) { // 业务逻辑 }
多文件上传(数组形式)
@parameter( description = "多文件上传", content = @content( mediatype = mediatype.multipart_form_data_value, array = @arrayschema( // 声明数组类型 schema = @schema(type = "string", format = "binary") ) ) ) @requestparam("files") multipartfile[] files
混合参数(文件+表单数据)
@requestbody( description = "混合参数请求", content = @content( mediatype = mediatype.multipart_form_data_value, encoding = { @encoding(name = "file", contenttype = "image/jpeg"), // 指定文件类型 @encoding(name = "remark", contenttype = "text/plain") // 文本参数 } ) ) @requestpart("file") multipartfile file, @requestpart("remark") string remark
分组与扩展功能
分组配置
按模块隔离接口
@bean public groupedopenapi publicapi() { return groupedopenapi.builder() .group("公开接口") .pathstomatch("/api/public/**") .build(); } @bean public groupedopenapi adminapi() { return groupedopenapi.builder() .group("管理接口") .pathstomatch("/api/admin/**") .addopenapimethodfilter(method -> method.isannotationpresent(preauthorize.class)) .build(); }
访问 swagger ui 右上角切换分组
生产环境安全建议
通过配置动态关闭文档
springdoc: swagger-ui: enabled: false # 生产环境禁用 ui api-docs: enabled: false # 禁用 openapi 端点:cite[1]
从 springfox 迁移指南
springfox 注解 | springdoc 替代方案 |
---|---|
@api | @tag |
@apioperation | @operation(summary="", description="") |
@apimodelproperty | @schema(description="") |
@apiparam | @parameter |
@apiignore | @hidden |
迁移优势:
- 支持 spring boot 3.x 和 jdk 17+;
- 注解更简洁,符合 openapi 3 规范
最佳实践与常见问题
依赖冲突
排除旧版 swagger 依赖(如
springfox-swagger2
),避免与 springdoc 冲突1。拦截器导致文档无法访问
若项目使用 spring security,需放行文档路径:
http.authorizerequests().antmatchers("/swagger-ui/**", "/v3/api-docs/**").permitall();
文档生成失败排查
检查控制器是否被扫描:确保
@restcontroller
位于springdoc.packages-to-scan
指定路径下
总结
springdoc 凭借 零配置启动、注解简洁 和 深度兼容 spring 生态 的优势,已成为 spring boot api 文档的首选工具。其核心价值在于:
- 自动化 - 减少手动维护文档的成本;
- 标准化 - 严格遵循 openapi 3 规范;
- 可扩展 - 分组、安全控制灵活适配复杂项目。
- 访问
http://localhost:8080/swagger-ui.html
即可查看交互式文档(默认路径)
到此这篇关于springdoc基本使用的方法示例的文章就介绍到这了,更多相关springdoc使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论