You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:启动项目后导出

  1. 点击IntelliJ右上角运行按钮启动Spring Boot项目。
  2. 项目启动成功后,打开底部Terminal,执行命令将文档保存为本地文件:
curl http://localhost:8080/v2/api-docs -o openapi-spec.yaml

(替换8080为项目实际端口)

方式2:通过Maven插件离线生成

无需启动项目,直接用Maven插件生成:

  1. 在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>
  1. 打开IntelliJ右侧Maven面板,找到项目下的Plugins > swagger > swagger:resolve,双击执行。
  2. 执行完成后,yaml文件会生成在target目录下,直接从项目结构中提取即可。

四、额外说明

  • 项目中已有的Swagger 2.0注解(如@Api、@ApiOperation)会被springdoc自动识别,纳入生成的文档。
  • 无自定义注解时,springdoc会基于Spring MVC控制器方法自动生成基础API结构。

内容的提问来源于stack exchange,提问作者BlueBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:53:20