2023年基于IntelliJ为Spring Boot3.0生成Swagger/OpenAPI2.0 YAML文件
为Spring Boot 3.0项目生成OpenAPI 2.0 YAML文件(IntelliJ IDE操作指南)
一、添加兼容依赖
Springfox已停止维护Spring Boot 3.x版本,推荐使用springdoc-openapi作为替代。在项目中添加以下依赖:
Maven(修改pom.xml)
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> <!-- 2023年稳定兼容版本 --> </dependency> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-webmvc-core</artifactId> <version>2.2.0</version> </dependency>
Gradle(修改build.gradle)
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0' implementation 'org.springdoc:springdoc-openapi-webmvc-core:2.2.0'
二、配置文档输出规则
在application.yml中添加配置,关闭Swagger UI并指定OpenAPI 2.0文档路径:
springdoc: swagger-ui: enabled: false # 禁用Swagger UI,符合需求 api-docs: enabled: true path: /v2/api-docs # Swagger 2.0格式的接口文档路径 writer-with-default-pretty-printer: true # 格式化输出内容
三、IntelliJ快速生成YAML文件
方式1:启动项目后导出
- 点击IntelliJ右上角运行按钮启动Spring Boot项目。
- 项目启动成功后,打开底部Terminal,执行命令将文档保存为本地文件:
curl http://localhost:8080/v2/api-docs -o openapi-spec.yaml
(替换8080为项目实际端口)
方式2:通过Maven插件离线生成
无需启动项目,直接用Maven插件生成:
- 在pom.xml的
build/plugins节点下添加插件:
<plugin> <groupId>io.swagger.core.v3</groupId> <artifactId>swagger-maven-plugin</artifactId> <version>2.2.0</version> <executions> <execution> <phase>compile</phase> <goals> <goal>resolve</goal> </goals> </execution> </executions> <configuration> <outputFileName>openapi-spec.yaml</outputFileName> <outputPath>${project.build.directory}</outputPath> <prettyPrint>true</prettyPrint> <openAPI30>false</openAPI30> <!-- 指定生成Swagger 2.0格式 --> <servers> <server> <url>http://localhost:8080</url> </server> </servers> </configuration> </plugin>
- 打开IntelliJ右侧Maven面板,找到项目下的
Plugins > swagger > swagger:resolve,双击执行。 - 执行完成后,yaml文件会生成在
target目录下,直接从项目结构中提取即可。
四、额外说明
- 项目中已有的Swagger 2.0注解(如
@Api、@ApiOperation)会被springdoc自动识别,纳入生成的文档。 - 无自定义注解时,springdoc会基于Spring MVC控制器方法自动生成基础API结构。
内容的提问来源于stack exchange,提问作者BlueBoy
相关产品推荐
相关产品推荐

