文章目录
- 一、概念解释
- 二、SpringDoc基本使用
- 三、SpringDoc进阶使用-配置文档信息
- 1、配置文档信息
- 2、springdoc的配置参数
- 1. API 文档基础配置
- 2.Swagger UI 配置
- springdoc.swagger-ui.enabled - 是否启用 Swagger UI-
- springdoc.swagger-ui.path - Swagger UI 路径
- springdoc.swagger-ui.config-url - 指定自定义的 OpenAPI 配置文件路径。
- springdoc.swagger-ui.disable-swagger-default-url - 是否禁用默认的 OpenAPI 文档 URL。
- springdoc.swagger-ui.oauth.client-id-配置 OAuth2 客户端 ID
- springdoc.swagger-ui.locale - Swagger UI 的界面语言切换为中文
- 3. 全局元信息-info
- 4. 分组与模块化
- 5. 安全配置
- 6. springdoc.cache.disabled - 自定义行为
- 7. 总结
- 8.配置实例
- 3、配置文档分组
- 四、SpringDoc进阶使用-SpringDoc全部注解
- 五、在实际项目上如何使用
系列文章:
springboot-swagger详解
springboot-优美的Knife4j文档-Swagger进化
Spring Cloud Gateway 网关整合 Knife4j
SpringBoot之如何集成SpringDoc最详细文档
一、概念解释
Swagger和Springdoc是两个常用的工具,用于生成和维护API文档,特别是针对基于REST的Web服务。它们有效地提升了API的可读性和可维护性,帮助开发者、产品经理和其他利益相关者更好地理解和使用所提供的API。
谈到API文档,那就绕不开大名鼎鼎的Swagger,但是你是否还听说过:OpenAPI,Springfox,Springdoc?你第一次看到这些脑瓜子是不是嗡嗡的?
1、OpenAPI
OpenApi 就像 JDBC 一样,制定了各种各样的规范,而 Swagger 和 SpringDoc 则类似于各种各样的数据库驱动,是具体的实现
-
定义 :OpenAPI 是一个开放标准,用于描述 RESTful API 的接口规范。它最初由 Swagger 项目发展而来,后来成为独立的标准(目前由 OpenAPI Initiative 维护)。
-
版本 :
- OpenAPI 2.0 :基于 Swagger 2.0 规范。
- OpenAPI 3.0+ :是更新的版本,引入了许多新特性(如增强的请求体描述、组件复用等)。
-
作用 :提供一种标准化的方式来描述 API 的结构、路径、参数、响应等内容,便于开发者和工具生成文档、测试接口。
2、Swagger
它是SmartBear这个公司的一个开源项目,里面提供了一系列工具,包括著名的 swagger-ui。
swagger是早于OpenApi的,某一天swagger将自己的API设计贡献给了OpenApi,然后由其标准化了。
- 定义 :Swagger 是一组围绕 OpenAPI 标准构建的工具集,包括代码生成器、UI 展示工具等。
- 版本 :
- Swagger 2.x :基于 OpenAPI 2.0,是最广泛使用的版本之一。
- Swagger 3.x :基于 OpenAPI 3.0+,支持更复杂的 API 描述功能。
- 工具 :
- Swagger UI :为 OpenAPI 文档提供交互式界面,方便开发者测试 API。
- Swagger Codegen :根据 OpenAPI 文档生成客户端代码或服务器端框架代码。
3、Springfox
是Spring生态的一个开源库,是Swagger与OpenApi规范的具体实现。我们使用它就可以在spring中生成API文档。以前基本上是行业标准,目前最新版本可以支持 Swagger2, Swagger3 以及 OpenAPI3 三种格式。但是其从 2020年7月14号就不再更新了,不支持springboot3,所以业界都在不断的转向我们今天要谈论的另一个库Springdoc,新项目就不要用了。
- 定义 :Springfox 是一个专门为 Spring 框架设计的库,用于自动生成基于 Swagger/OpenAPI 的 API 文档。
- 特点 :
- 支持 Spring MVC 和 Spring Boot。
- 主要基于 Swagger 2.x 和 OpenAPI 2.0 。
- 通过注解(如 @Api、@ApiOperation 等)来描述 API。
- 局限性 :
- 对 OpenAPI 3.0 的支持较弱(尽管有实验性支持,但不够完善)。
- 在 Spring Boot 2.6 及更高版本中,由于兼容性问题(如路径匹配策略的变化),Springfox 的使用变得复杂甚至不可行。
4、Springdoc
算是后起之秀,带着继任Springfox的使命而来。其支持OpenApi规范,支持Springboot3,我们的新项目都应该使用这个。
- 定义 :Springdoc 是一个现代化的开源库,专为 Spring Boot 应用程序设计,用于自动生成基于 OpenAPI 3.0+ 的 API 文档。
- 特点 :
- 原生支持 OpenAPI 3.0+ ,并提供对 Spring Boot 2.6+ 的良好兼容性。
- 使用标准的 OpenAPI 注解(如 @Operation、@Parameter 等),而不是 Swagger 特有的注解。
- 提供内置的 Swagger UI,方便开发者快速查看和测试 API。
- 优势 :
- 更轻量、更易配置。
- 更好的性能和兼容性。
- 社区活跃,更新频繁。
SpringDoc 支持:
- OpenAPI 3
- Spring-boot,全版本都支持。
- JSR-303 中提供的一些注解,例如 @NotNull、@Min、@Max 以及 @Size 等。
- Swagger-ui:SpringDoc 提供的接口 JSON 也可以通过 Swagger-ui 展示出来。
- OAuth 2
- …
5. 关系与区别
特性 | Springfox | Springdoc | Swagger | OpenAPI |
---|---|---|---|---|
主要用途 | 自动生成 API 文档 | 自动生成 API 文档 | 工具集,用于生成文档和测试 API | API 描述标准 |
支持的规范 | Swagger 2.x / OpenAPI 2.0 | OpenAPI 3.0+ | Swagger 2.x / Swagger 3.x | OpenAPI 2.0 / OpenAPI 3.0+ |
Spring Boot 兼容性 | 较差(尤其是 2.6+ 版本) | 良好 | 不直接相关 | 不直接相关 |
注解 | 使用 Swagger 特定注解(如 @Api ) | 使用 OpenAPI 标准注解(如 @Operation ) | 使用 Swagger 特定注解 | 定义了标准注解 |
工具支持 | 提供 Swagger UI | 提供 Swagger UI | 提供 Swagger UI 和 Codegen | 无直接工具支持,需依赖实现(如 Swagger) |
社区活跃度 | 逐渐减少 | 高 | 高 | 高 |
二、SpringDoc基本使用
我们可以在springboot中使用SpringDoc来生成API文档,详情可以参考官网,下面我们来简单的实践一下。
1、导包
在springboot中使用springdoc起步非常容易,只需要引入其starter即可
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version> <!-- 版本可替换 -->
</dependency>
2、正常编写代码,不需要任何注解
3、运行后访问下面的链接即可
http://server:port/context-path/swagger-ui.html
例如:
http://localhost:9204/swagger-ui.html
虽然上边配置的SpringDoc很好用,但是对比swagger我们就知道,缺少了很多信息,当然springdoc的集成不可能就这点东西,不然也没有这篇文章了。
三、SpringDoc进阶使用-配置文档信息
1、配置文档信息
得益于springboot的强大,我们只需添加一个依赖就可以使用API文档了,但是使用的都是默认值,我们当然也希望对其进行各种自定义的配置
创建一个OpenAPI 的bean,配置文档名称等信息
package com.wenge.business.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Swagger 文档配置
*
* @author wkl
*/
@Configuration
public class SpringDocAutoConfiguration {
@Bean
public OpenAPI openApi() {
return new OpenAPI()
.info(new Info()
.title("这是标题")
.description("这是备注")
.version("这是版本")
.license(new License()
.name("这是许可证")
.url("这是许可证链接"))
.contact(new Contact()
.name("这是作者")
.url("这是作者链接")
.email("这是作者email"))
);
}
}
2、springdoc的配置参数
但是我们在实际应用中不会把这些配置参数写死在代码里,所以springdoc为我们设置好了配置参数,只需要写在application.xml
或者bootstrap.yml
中即可。
1. API 文档基础配置
springdoc.api-docs.enabled - 是否启用 API 文档-
springdoc.api-docs.enabled
- 作用:启用或禁用 OpenAPI 文档生成功能。
- 默认值:
true
- 效果
如果设置为false
,将禁用/v3/api-docs
端点,无法访问 OpenAPI JSON 数据。 - 示例:
springdoc.api-docs.enabled=false
springdoc.api - docs.path-API 文档路径
springdoc.api-docs.path
- 作用:指定 OpenAPI JSON 文档的访问路径。
- 默认值:
/v3/api-docs
- 效果
访问路径变为/openapi.json
,例如:http://localhost:8080/openapi.json
。 - 示例:
springdoc.api-docs.path=/openapi.json
springdoc.api-docs.groups.enabled - 是否启用分组功能,支持多个 API 分组
-
作用:是否启用分组功能,支持多个 API 分组。
-
默认值:
false
-
示例:
springdoc.api-docs.groups.enabled=true
-
效果:
启用后,可以通过分组区分不同的 API 文档(如公共 API 和管理员 API)。
2.Swagger UI 配置
springdoc.swagger-ui.enabled - 是否启用 Swagger UI-
springdoc.swagger-ui.enabled
- 作用:启用或禁用 Swagger UI。
- 默认值:
true
- 效果
如果设置为false
,将禁用 Swagger UI 页面(通常位于/swagger-ui.html
)。 - 示例:
springdoc.swagger-ui.enabled=false
尽管 OpenAPI 文档本身已经包含了完整的 API 描述信息,但 Swagger UI 提供了一个更友好的界面,使得开发者可以更方便地浏览和测试 API。以下是一些常见的 Swagger UI 配置及其作用:
Swagger UI 是 OpenAPI 文档的补充工具,它将 API 文档以图形化的方式呈现出来,并提供了交互式功能,极大地方便了开发者的使用。虽然 OpenAPI 文档本身已经足够强大,但 Swagger UI 让文档更加直观、易用。
springdoc.swagger-ui.path - Swagger UI 路径
springdoc.swagger-ui.path
-
作用:指定 Swagger UI 的访问路径。
-
默认值:
/swagger-ui.html
-
效果
Swagger UI 的访问路径变为/docs
,例如:http://localhost:8080/docs
。 -
示例:
springdoc.swagger-ui.path=/docs
-
springdoc.swagger-ui.config-url - 指定自定义的 OpenAPI 配置文件路径。
-
默认值:无
-
示例
springdoc.swagger-ui.config-url=/custom-config.json
-
效果
Swagger UI 将加载自定义配置文件/custom-config.json
。
springdoc.swagger-ui.disable-swagger-default-url - 是否禁用默认的 OpenAPI 文档 URL。
-
默认值:
false
-
示例
springdoc.swagger-ui.disable-swagger-default-url=true
-
效果
禁用后,Swagger UI 不会自动加载默认的/v3/api-docs
URL。
springdoc.swagger-ui.oauth.client-id-配置 OAuth2 客户端 ID
-
作用:配置 OAuth2 客户端 ID,用于 Swagger UI 的 OAuth2 登录。
-
默认值:无
-
示例:
springdoc.swagger-ui.oauth.client-id=my-client-id springdoc.swagger-ui.oauth.client-secret=my-secret
-
效果:
在 Swagger UI 中显示 OAuth2 登录选项,并使用配置的客户端信息进行认证。
springdoc.swagger-ui.locale - Swagger UI 的界面语言切换为中文
-
作用:设置 Swagger UI 的语言。
-
默认值:
en
-
示例:
springdoc.swagger-ui.locale=zh-CN
-
效果:
Swagger UI 的界面语言切换为中文。
3. 全局元信息-info
springdoc.info.title - 应用标题
springdoc.info.title
- 作用:设置 API 文档的标题。
- 默认值:空
- 示例:
springdoc.info.title=用户管理系统
springdoc.info.description - 应用描述
springdoc.info.description
- 作用:设置 API 文档的描述信息。
- 默认值:空
- 示例:
springdoc.info.description=用户管理相关的 API 文档
pringdoc.info.version - 版本号
springdoc.info.version
- 作用:设置 API 文档的版本号。
- 默认值:空
- 示例:
springdoc.info.version=1.0.0
springdoc.info.contact - 联系人信息
springdoc.info.contact.name
springdoc.info.contact.email
springdoc.info.contact.url
- 作用:设置文档的联系人信息(姓名、邮箱、URL)。
- 默认值:空
- 示例:
springdoc.info.contact.name=John Doe springdoc.info.contact.email=john.doe@example.com springdoc.info.contact.url=http://example.com
springdoc.info.contact.name
-
作用:定义联系人名称。
-
默认值:无
-
示例:
springdoc.info.contact.name=Support Team
-
效果:
在生成的 OpenAPI 文档中显示联系人信息。
springdoc.info.contact.email
-
作用:定义联系人的邮箱地址。
-
默认值:无
-
示例:
springdoc.info.contact.email=support@example.com
-
效果:
在生成的 OpenAPI 文档中显示联系人邮箱。
pringdoc.info.license - 许可信息
springdoc.info.license.name
springdoc.info.license.url
- 作用:设置文档的许可证信息(名称、URL)。
- 默认值:空
- 示例:
springdoc.info.license.name=Apache 2.0 springdoc.info.license.url=https://www.apache.org/licenses/LICENSE-2.0
springdoc.info.license.name
-
作用:定义许可证名称。
-
默认值:无
-
示例:
springdoc.info.license.name=Apache 2.0
-
效果:
在生成的 OpenAPI 文档中显示许可证信息。
springdoc.info.license.url
-
作用:定义许可证链接。
-
默认值:无
-
示例:
springdoc.info.license.url=https://www.apache.org/licenses/LICENSE-2.0.html
-
效果:
在生成的 OpenAPI 文档中显示许可证链接。
4. 分组与模块化
springdoc.group-configs - 分组支持
springdoc.group-configs
- 作用:为不同的控制器或包生成独立的 API 文档分组。
- 示例:
springdoc.group-configs[0].group=user-api #定义分组名称。 springdoc.group-configs[0].paths-to-match=/api/user/** #定义分组匹配的路径。 springdoc.group-configs[1].group=order-api springdoc.group-configs[2].paths-to-match=/api/order/** #定义分组匹配的路径。
springdoc.group-configs[0].group
-
作用:定义分组名称。
-
默认值:无
-
示例:
springdoc.group-configs[0].group=public
-
效果:
创建一个名为public
的分组。
springdoc.group-configs[0].paths-to-match
-
作用:定义分组匹配的路径。
-
默认值:无
-
示例:
springdoc.group-configs[0].paths-to-match=/api/public/**
-
效果:
仅包含路径匹配/api/public/**
的 API。
springdoc.packages-to-scan - 扫描包范围
springdoc.packages-to-scan
- 作用:指定需要扫描的包范围,用于生成 API 文档。
- 默认值:当前应用程序的所有包。
- 效果:
仅扫描com.example.api
包中的控制器生成文档。 - 示例:
springdoc.packages-to-scan=com.example.api
springdoc.paths-to-exclude - 排除特定路径
springdoc.paths-to-exclude
- 作用:排除某些路径,不将其包含在生成的 API 文档中。
- 默认值:无
- 效果:
排除所有以/admin/
开头的路径。 - 示例:
springdoc.paths-to-exclude=/admin/**
5. 安全配置
springdoc.api-docs.security-schemes - 全局安全方案
springdoc.api-docs.security-schemes
- 作用:定义全局的安全方案(如 OAuth2、API Key 等)。
- 示例:
springdoc.api-docs.security-schemes[0].name=ApiKeyAuth springdoc.api-docs.security-schemes[0].type=apiKey springdoc.api-docs.security-schemes[0].in=header
springdoc.api-docs.security-requirements - 全局安全要求
springdoc.api-docs.security-requirements
- 作用:定义全局的安全要求。
- 示例:
springdoc.api-docs.security-requirements[0]=ApiKeyAuth
6. springdoc.cache.disabled - 自定义行为
springdoc.cache.disabled - 缓存控制
springdoc.cache.disabled
- 作用:禁用 API 文档的缓存。
- 默认值:
false
- 效果:
每次请求都会重新生成 OpenAPI 文档。 - 示例:
springdoc.cache.disabled=true
springdoc.default-flat-param-object - 排序规则
springdoc.default-flat-param-object
- 作用:是否将参数对象展平为单个参数。
- 默认值:
false
- 示例:
springdoc.default-flat-param-object=true
springdoc.servers - 服务器地址-pringdoc.servers
- 作用:
- 定义 OpenAPI 文档中的 servers 字段
springdoc.servers 允许你在 OpenAPI 文档中显式列出一个或多个服务器地址(URL),并为每个地址添加描述信息。
- 支持多环境或多网关配置
如果你的 API 在不同的环境中运行(如开发、测试、生产)或者通过多个网关访问,可以通过 springdoc.servers 配置所有可能的服务器地址。
- 定义 OpenAPI 文档中的 servers 字段
- 示例:
springdoc.servers[0].url=http://localhost:8080 springdoc.servers[0].description=本地开发环境 springdoc.servers[1].url=https://api.example.com springdoc.servers[1].description=生产环境
- 效果:
Swagger UI 会显示一个下拉菜单,列出所有配置的服务器地址。
开发者可以选择某个服务器地址进行 API 调用。
适用于多环境或多网关的场景。
springdoc.gatewayUrl - 通过网关使用地址
- 作用
- 自动修正 OpenAPI 文档中的服务器地址为网关地址
当你使用 Spring Cloud Gateway 或其他网关时,客户端实际访问的 API 地址是通过网关路由映射的,而不是后端服务的真实地址。springdoc.gatewayUrl 用于告诉 SpringDoc 客户端应该通过哪个网关地址访问 API。 - 简化配置
不需要手动列出多个服务器地址,只需要指定一个网关的基础 URL。
- 自动修正 OpenAPI 文档中的服务器地址为网关地址
- 示例
springdoc:
gatewayUrl: http://gateway.example.com
- 效果
- Swagger UI 中的服务器地址会被修正为网关地址(http://gateway.example.com)。
- API 路径会根据网关的路由规则自动调整(如 /api/v1/example)。
- 适用于单网关的场景。
对比分析:springdoc.servers
vs springdoc.gatewayUrl
特性 | springdoc.servers | springdoc.gatewayUrl |
---|---|---|
功能 | 定义 OpenAPI 文档中的 servers 字段,支持多个地址 | 自动修正文档中的服务器地址为网关地址 |
适用场景 | 多环境(开发、测试、生产)、多网关 | 单网关场景 |
是否支持多地址 | 支持多个服务器地址 | 只支持一个网关地址 |
是否需要手动配置路径 | 需要手动配置路径和描述信息 | 自动适配网关的路由规则 |
优先级 | 如果同时配置了两者,springdoc.servers 优先级更高 | 会被 springdoc.servers 覆盖 |
springdoc.gatewayUrl
:适合单网关场景,自动修正服务器地址为网关地址,并适配网关的路由规则。springdoc.servers
:适合多环境或多网关场景,允许显式列出多个服务器地址,并为每个地址添加描述信息。- 如果需要更灵活的配置,建议使用
springdoc.servers
;如果只是简单地适配网关,可以使用springdoc.gatewayUrl
。
7. 总结
以下是 springdoc
配置参数的分类总结:
类别 | 参数 | 作用 |
---|---|---|
基础配置 | springdoc.api-docs.path , springdoc.swagger-ui.path , springdoc.api-docs.enabled | 配置 API 文档路径、Swagger UI 路径及启用状态。 |
全局元信息 | springdoc.info.title , springdoc.info.description , springdoc.info.version | 设置 API 文档的标题、描述、版本等基本信息。 |
分组与模块化 | springdoc.group-configs , springdoc.packages-to-scan , springdoc.paths-to-exclude | 支持分组、限制扫描范围、排除特定路径。 |
安全配置 | springdoc.api-docs.security-schemes , springdoc.api-docs.security-requirements | 定义全局安全方案和要求。 |
自定义行为 | springdoc.cache.disabled , springdoc.default-flat-param-object , springdoc.servers | 控制缓存、参数对象展平、服务器地址等高级功能。 |
高级配置 | 自定义 OpenAPI 对象、Swagger UI 配置 | 通过代码方式实现更灵活的定制。 |
8.配置实例
springdoc:
api-docs:
enabled: true
path: /openapi.json
groups:
enabled: true
swagger-ui:
enabled: true
path: /docs
config-url: /custom-config.json
disable-swagger-default-url: false
oauth:
client-id: my-client-id
client-secret: my-secret
locale: zh-CN
info:
title: User API
description: API for managing users
version: 1.0
contact:
name: Support Team
email: support@example.com
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
group-configs:
- group: public
paths-to-match: /api/public/**
- group: admin
paths-to-match: /api/admin/**
packages-to-scan: com.example.api
paths-to-exclude: /internal/**
oauth2:
client-id: oauth-client-id
client-secret: oauth-client-secret
cache:
disabled: false
writer-with-default-pretty-printer: true
3、配置文档分组
用来配置分组的,假如你有多类controller一类以/tacticsInfo为前缀分组,一类以/admin为前缀,就可以将其配置为两个分组。很多时候我们只有一个分组,所以就不需要下面的配置。
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("tacticsInfo")
.pathsToMatch("/tacticsInfo/**")//以/tacticsInfo开头的的api都进这个分组
.build();
}
@Bean
public GroupedOpenApi otherApi() {
return GroupedOpenApi.builder()
.group("other")
.pathsToMatch("/admin/**")//以/admin开头的的api都进这个分组
.build();
}
// @Bean
// public GroupedOpenApi otherApi() {
// return GroupedOpenApi.builder()
// .group("other")
// .pathsToMatch("/**/**")//这样配置,那就是所有的api都进这个分组
// .build();
// }
可以通过右上角的下拉框选择要展示的group。
四、SpringDoc进阶使用-SpringDoc全部注解
1. 核心注解
@Tag-Class类上
-
作用:为控制器或方法分组,便于组织和分类 API。
-
常用属性:
name
:标签名称。description
:标签描述信息。externalDocs
:外部文档链接(@ExternalDocumentation
类型)。
-
示例:
@Tag(name = "策略库接口",description = "这是策略库的所有接口") @RestController @RequestMapping("/tacticsInfo") public class TacticsInfoController extends BaseController { // ... }
通过@Tag 的 name 属性进行分组排序
注:springdoc 本身并没有提供直接用于排序的注解,但可以通过以下方式实现对 API 文档的排序
- 在生成的 OpenAPI 文档中,@Tag 的 name 属性会影响分组的顺序。按字母顺序排列。
- 如果需要自定义顺序,可以在 name 中添加前缀(如数字)来控制顺序。
@Tag(name = "1. User", description = "用户相关操作")
@RestController
@RequestMapping("/users")
public class UserController { }
@Tag(name = "2. Order", description = "订单相关操作")
@RestController
@RequestMapping("/orders")
public class OrderController { }
2. 方法级别注解
@Operation-方法描述
- 作用:描述一个 API 方法的功能。
- 常用属性:
summary
:操作的简短描述。description
:操作的详细描述。tags
:所属的标签(数组)。operationId
:唯一标识符,用于区分不同的操作。responses
:定义响应信息(@ApiResponse
类型)。parameters
:定义请求参数(@Parameter
类型)。requestBody
:定义请求体(@RequestBody
类型)。deprecated
:是否标记为已废弃(布尔值)。security
:定义安全要求(@SecurityRequirement
类型)。hidden
:是否隐藏该操作(布尔值)。
- 示例:
@Operation(summary = "查询策略库:tactics_info列表",description = "查询策略库:tactics_info列表-list接口") @RequiresPermissions("business:tacticsInfo:list") @GetMapping("/list") public TableDataInfo list(TacticsInfo tacticsInfo) { // ... }
@ApiResponse 和 @ApiResponses-方法的返回结果
- 作用:描述 API 方法的响应结果。
- 常用属性:
responseCode
:HTTP 响应码(如 “200”、“404”)。description
:响应的描述信息。content
:响应的内容类型(@Content
类型)。headers
:响应头信息(@Header
类型)。links
:链接信息(@Link
类型)。
- 示例:
@Operation(summary = "创建用户", description = "根据用户信息创建新用户") @ApiResponses({ @ApiResponse(responseCode = "200", description = "成功创建用户"), @ApiResponse(responseCode = "400", description = "请求参数错误"), @ApiResponse(responseCode = "500", description = "服务器内部错误") }) @PostMapping public ResponseEntity<User> createUser(@RequestBody User user) { // ... }
3. 参数相关注解
@Parameter-方法参数
- 作用:描述方法参数的含义。
- 常用属性:
name
:参数名称。description
:参数描述信息。required
:是否必填。example
:参数示例值。in
:参数位置(如path
、query
、header
等)。
- 示例:
@Operation(summary = "根据 ID 获取用户") @GetMapping("/{id}") public User getUserById( @Parameter(name = "id", description = "用户 ID", required = true, example = "1") @PathVariable Long id) { // ... }
@Parameters方法参数(单个)
- 作用:描述多个参数。
- 常用属性:
name
:参数名称。description
:参数的描述信息。in
:参数的位置(如 “query”、“path”、“header”、“cookie”)。required
:是否为必填参数(布尔值)。schema
:参数的数据类型(@Schema
类型)。example
:示例值。deprecated
:是否标记为已废弃(布尔值)。
- 示例:
@Operation(summary = "搜索用户") @Parameters({ @Parameter(name = "name", description = "用户名", in = ParameterIn.QUERY), @Parameter(name = "age", description = "用户年龄", in = ParameterIn.QUERY) }) @GetMapping("/search") public List<User> searchUsers(@RequestParam String name, @RequestParam Integer age) { // ... }
@RequestBody
- 作用:用于描述 API 的请求体。
- 常用属性
description
:请求体的描述信息。content
:请求体的内容类型(@Content
类型)。required
:是否为必填请求体(布尔值)。
- 示例
@RequestBody(
description = "User object to be created",
required = true,
content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))
)
4. 实体模型相关注解
@Schema-描述实体类或字段的信息
- 作用:描述实体类或字段的信息。
- 常用属性:
type
:字段的数据类型(如 “string”、“integer”、“array”)。format
:字段的格式(如 “date-time”、“int64”)。description
:字段的描述信息。example
:字段的示例值。defaultValue
:字段的默认值。required
:是否为必填字段(布尔值)。deprecated
:是否标记为已废弃(布尔值)。enum
:枚举值列表。implementation
:指定类作为模型(仅用于复杂对象)。
- 示例:
@Schema(description = "用户的基本信息") public class User { @Schema(description = "用户 ID", example = "1", required = true) private Long id; @Schema(description = "用户名", example = "John Doe", required = true) private String name; @Schema(description = "用户年龄", example = "25") private Integer age; // getters and setters }
5. 其他注解
@Hidden-隐藏某个类、方法或参数
- 作用:隐藏某个类、方法或参数,不将其包含在生成的文档中。
- 示例:
@Hidden @GetMapping("/internal") public String internalEndpoint() { return "This endpoint is ignored by springdoc."; }
6. 配置相关注解(不常用)
@OpenAPIDefinition-全局配置 OpenAPI 文档的元信息
- 作用:全局配置 OpenAPI 文档的元信息。这个不常用,还是常用配置文件类型的
- 常用属性:
info
:文档的基本信息(标题、版本、描述等)。tags
:全局标签定义。servers
:API 的服务器地址。externalDocs
:外部文档链接(@ExternalDocumentation
类型)。
- 示例:
@OpenAPIDefinition( info = @Info(title = "用户管理系统", version = "1.0", description = "用户相关的 API 文档"), tags = { @Tag(name = "用户管理", description = "与用户相关的操作") }, servers = { @Server(url = "http://localhost:8080", description = "本地开发环境") } ) @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
7. 数据模型相关注解
@ArraySchema-用于描述数组类型的字段。
-
参数
array
:数组的元素类型(@Schema
类型)。uniqueItems
:是否唯一(布尔值)。minItems
:最小元素数量。maxItems
:最大元素数量。
-
示例
@ArraySchema(
array = @Schema(type = "string"),
uniqueItems = true,
minItems = 1,
maxItems = 10
)
private List<String> tags;
@Xml-用于描述 XML 相关的元数据。
-
参数
name
:XML 元素名称。namespace
:XML 命名空间。prefix
:XML 前缀。attribute
:是否为属性(布尔值)。
-
示例
@Xml(name = "user", namespace = "http://example.com/user")
private User user;
7. 总结
以下是 springdoc
常用注解的分类总结:
注解 | 作用 |
---|---|
@Tag | 为控制器或方法分组,便于组织和分类 API。 |
@Operation | 描述 API 方法的功能。 |
@ApiResponse | 描述单个响应结果。 |
@Parameter | 描述方法参数的含义。 |
@Schema | 描述实体类或字段的信息。 |
@Hidden | 隐藏某个类、方法或参数,不包含在生成的文档中。 |
@OpenAPIDefinition | 全局配置 OpenAPI 文档的元信息(标题、版本、描述等)。 |
五、在实际项目上如何使用
1、导包
在springboot中使用springdoc起步非常容易,只需要引入其starter即可
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version> <!-- 版本可替换 -->
</dependency>
2、写配置类
1)、配置实体类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.License;
/**
* Swagger 配置属性
*
* @author wkl
*/
@ConfigurationProperties(prefix = "springdoc")
public class SpringDocProperties
{
/**
* 网关
*/
private String gatewayUrl;
/**
* 文档基本信息
*/
@NestedConfigurationProperty
private InfoProperties info = new InfoProperties();
/**
* <p>
* 文档的基础属性信息
* </p>
*
* @see io.swagger.v3.oas.models.info.Info
*
* 为了 springboot 自动生产配置提示信息,所以这里复制一个类出来
*/
public static class InfoProperties
{
/**
* 标题
*/
private String title = null;
/**
* 描述
*/
private String description = null;
/**
* 联系人信息
*/
@NestedConfigurationProperty
private Contact contact = null;
/**
* 许可证
*/
@NestedConfigurationProperty
private License license = null;
/**
* 版本
*/
private String version = null;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Contact getContact()
{
return contact;
}
public void setContact(Contact contact)
{
this.contact = contact;
}
public License getLicense()
{
return license;
}
public void setLicense(License license)
{
this.license = license;
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
}
public String getGatewayUrl()
{
return gatewayUrl;
}
public void setGatewayUrl(String gatewayUrl)
{
this.gatewayUrl = gatewayUrl;
}
public InfoProperties getInfo()
{
return info;
}
public void setInfo(InfoProperties info)
{
this.info = info;
}
}
2)、配置类
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import com.wenge.common.swagger.config.properties.SpringDocProperties;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
/**
* Swagger 文档配置
*
* @author ruoyi
*/
@EnableConfigurationProperties(SpringDocProperties.class)
@ConditionalOnProperty(name = "springdoc.api-docs.enabled", havingValue = "true", matchIfMissing = true)
public class SpringDocAutoConfiguration
{
@Bean
@ConditionalOnMissingBean(OpenAPI.class)
public OpenAPI openApi(SpringDocProperties properties) {
return new OpenAPI()
// 设置认证的请求头,在 Components 中注册一个安全方案
.components(new Components().addSecuritySchemes("apikey", securityScheme()))
//在 OpenAPI 文档中添加一个安全需求,声明 API 调用时需要满足的安全方案
.addSecurityItem(new SecurityRequirement().addList("apikey"))
.info(convertInfo(properties.getInfo()));//
// .servers(servers(properties.getGatewayUrl()));
}
public SecurityScheme securityScheme() {
return new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)//类型:通过 API Key 进行认证
.name("Authorization")//设置 API Key 的名称为 "Authorization"
.in(SecurityScheme.In.HEADER)//指定 API Key 的传递位置为 HTTP 请求头
.scheme("Bearer");//设置安全方案的具体协议为 "Bearer"
}
private Info convertInfo(SpringDocProperties.InfoProperties infoProperties)
{
Info info = new Info();
info.setTitle(infoProperties.getTitle());
info.setDescription(infoProperties.getDescription());
info.setContact(infoProperties.getContact());
info.setLicense(infoProperties.getLicense());
info.setVersion(infoProperties.getVersion());
return info;
}
public List<Server> servers(String gatewayUrl)
{
List<Server> serverList = new ArrayList<>();
serverList.add(new Server().url(gatewayUrl));
return serverList;
}
}
3、编写配置参数
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
enabled: true
operationsSorter: method
show-actuator: true