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

Java 8 Spring项目构建时自动生成Swagger单JSON文件方案咨询

实现构建时自动生成Swagger JSON文件的方案

绝对可以实现!针对你的Java 8 Spring项目(已配置Swagger网页文档),要在每次构建时同步生成包含所有端点的单个JSON文件,下面分享两种主流且可靠的实现方式,适配你的技术栈:

方案一:自定义代码+构建插件触发(灵活可控)

这种方式适合希望通过代码自定义生成逻辑的场景,不需要引入过多第三方依赖:

  1. 编写Swagger JSON生成工具类
    创建一个独立主类,利用Swagger的Swagger对象和Jackson序列化工具生成JSON文件,避免依赖应用启动时执行:
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.Swagger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.io.File;
import java.io.IOException;

// 替换成你的项目根包路径,确保能扫描到Swagger配置类和控制器
@ComponentScan(basePackages = "com.your.project.root")
public class SwaggerJsonGenerator {

    public static void main(String[] args) throws IOException {
        // 启动Spring上下文获取Swagger实例
        try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SwaggerJsonGenerator.class)) {
            Swagger swagger = context.getBean(Swagger.class);
            ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
            
            // 指定生成路径,比如构建目录下的swagger-output.json
            File outputFile = new File(System.getProperty("user.dir") + "/target/swagger-output.json");
            // 格式化输出JSON,方便阅读
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputFile, swagger);
        }
    }
}
  1. 配置Maven插件绑定构建阶段
    在pom.xml中添加exec-maven-plugin,让它在compile阶段自动执行上述主类,这样每次执行mvn clean install时都会生成JSON:
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <id>generate-swagger-json</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <configuration>
                        <!-- 替换成你的SwaggerJsonGenerator类的全路径 -->
                        <mainClass>com.your.project.root.SwaggerJsonGenerator</mainClass>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

方案二:使用Swagger官方构建插件(简洁高效)

如果不想编写自定义代码,可以直接用Swagger官方提供的Maven/Gradle插件,自动扫描控制器生成JSON:

Maven版本配置

在pom.xml中添加swagger-maven-plugin,配置扫描路径、输出格式和位置:

<build>
    <plugins>
        <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-maven-plugin</artifactId>
            <!-- 1.6.2版本兼容Java 8,避免用过高版本导致兼容性问题 -->
            <version>1.6.2</version>
            <configuration>
                <apiSources>
                    <apiSource>
                        <springmvc>true</springmvc> <!-- 标记为Spring MVC项目 -->
                        <!-- 替换成你的控制器所在包路径 -->
                        <locations>com.your.project.controller</locations>
                        <schemes>http,https</schemes>
                        <host>localhost:8080</host> <!-- 你的API服务地址 -->
                        <basePath>/api</basePath> <!-- API基础路径 -->
                        <info>
                            <title>Your Project API Docs</title>
                            <version>1.0.0</version>
                        </info>
                        <outputFormats>json</outputFormats> <!-- 指定生成JSON格式 -->
                        <!-- 输出到构建目录,避免提交到版本库 -->
                        <outputPath>${project.build.directory}/swagger.json</outputPath>
                    </apiSource>
                </apiSources>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

执行mvn compile或mvn install时,插件会自动扫描所有控制器,生成包含全部端点的JSON文件。

Gradle版本配置(如果用Gradle构建)

添加Swagger Gradle插件并配置:

plugins {
    id 'java'
    // 兼容Java 8的插件版本
    id 'io.swagger.core.v3.swagger-gradle-plugin' version '2.2.10'
}

swagger {
    api {
        info {
            title = 'Your Project API Docs'
            version = '1.0.0'
        }
        servers {
            server {
                url = 'http://localhost:8080/api'
            }
        }
        outputFileName = 'swagger.json'
        outputDir = file("${buildDir}/swagger")
        springmvc = true
        // 替换成你的控制器包路径
        locations = ['com.your.project.controller']
    }
}

// 将生成任务绑定到build阶段
tasks.build.dependsOn(tasks.swagger)

关键注意事项

  • 确保你的Swagger配置类(通常是SwaggerConfig)已经添加@EnableSwagger2注解,并且正确扫描了所有控制器类,否则生成的JSON会遗漏端点。
  • 对于Java 8,务必选择兼容的插件版本,避免使用仅支持Java 11+的高版本插件。
  • 建议将生成的JSON文件输出到构建目录(如target或build),不要提交到版本库,保持代码库整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:44:38