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

如何在构建阶段为Spring Rest项目生成无需启动的OpenApi 3接口文档

无需启动Spring项目生成OpenApi 3规范文档的实现方案

以下是两种可在构建阶段直接生成文档的成熟方案,均不需要启动完整Spring项目:

  • 方案1:使用高版本springdoc maven插件的离线模式
    springdoc 1.6及以上版本的maven插件已经原生支持无需启动Spring Boot应用的离线生成能力,仅会静态扫描项目注解,不会启动内嵌web容器,对Spring生态注解的兼容性最好,无需额外适配就能识别@RestController、@GetMapping、@RequestParam等Spring Web原生注解,配置示例如下:
<plugin>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-maven-plugin</artifactId>
    <version>最新稳定版</version>
    <configuration>
        <!-- 关闭Spring Boot应用启动逻辑 -->
        <skipSpringBoot>true</skipSpringBoot>
        <!-- 指定需要扫描的Controller包路径 -->
        <apiPackages>com.yourproject.controller</apiPackages>
        <!-- 配置生成的文档输出路径和文件名 -->
        <outputFileName>openapi.json</outputFileName>
        <outputDir>${project.build.directory}</outputDir>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
  • 方案2:使用Swagger官方静态扫描maven插件
    可以直接使用io.swagger.core.v3:swagger-maven-plugin,该插件完全基于注解静态扫描生成文档,全程不需要启动任何Spring相关上下文,配置示例如下:
<plugin>
    <groupId>io.swagger.core.v3</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>2.2.15</version>
    <configuration>
        <outputFileName>openapi</outputFileName>
        <outputPath>${project.build.directory}</outputPath>
        <outputFormat>JSON</outputFormat>
        <resourcePackages>com.yourproject.controller</resourcePackages>
        <prettyPrint>true</prettyPrint>
        <openApiConfiguration>
            <info>
                <title>项目接口文档</title>
                <version>1.0.0</version>
            </info>
        </openApiConfiguration>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>resolve</goal>
            </goals>
        </execution>
    </executions>
</plugin>

注意:如果你的项目中存在编程式注册的接口、动态路径映射等非注解式定义的接口,静态扫描方案无法识别这类接口,需要配合轻量Spring上下文启动的模式生成完整文档,普通注解定义的Rest接口都可以通过上述方案覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:39:00