如何在 debug/run 上的 IntelliJ "out" 目录中为 Spring 引导项目生成 build-info.properties?

How do I generate build-info.properties in the IntelliJ "out" directory on debug/run for a Spring Boot project?

在我的 build.gradle 中,我添加了 spring 构建信息:

springBoot {
    mainClass = "${springBootMainClass}"

    buildInfo() {
        additionalProperties = [
                name: "${appName}",
                version: "${version}-${buildNumber}",
                time: buildTime()
        ]
    }
}

def buildTime() {
    final dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
    dateFormat.timeZone = TimeZone.getTimeZone('GMT')
    dateFormat.format(new Date())
}

当我从命令行 运行 时,这会正确地将 /META-INF/build-info.properties 文件添加到 /build/resources/main 中,以便 "/info" 端点在 [=35] 中显示构建信息=].

当我从 IntelliJ 的 run/debug 按钮 运行 时,IntelliJ 使用 /build 目录而是使用 /out 目录也没有 运行 那个 gradle 任务,所以 /info 端点有空 JSON.

如何让它生成该文件并将其放入 /out 目录?

启用将IDEbuild/run操作委托给设置(首选项)中的Gradle选项|构建、执行、部署 |构建工具 | Gradle | Runner 选项卡。

在最新的 IDE 版本中,设置 Gradle(macOS 上的首选项)|构建、执行、部署 |构建工具 | Gradle | 使用选项构建并运行。

我有完全相同的需求,出于不同的(好的)原因,我不想使用“将 IDE build/run 操作委托给 Gradle”。

在我的例子中,我不需要那个文件 /META-INF/build-info.properties 在开发阶段 IDEA 中 up-to-date,我只需要这个文件在“运行" 类路径(在 /out/... 下),否则 Spring 在从 IDEA run/debug 工具.

如果你也是我的情况,这里有一个简单的解决方案:

  1. 在主资源目录 (src/main/resources/META-INF/build-info.properties)

    中创建 build-info.properties 的虚拟“开发”(或“快照”)版本

    #请勿编辑(将被 Spring 引导插件覆盖) build.time=2019-05-07T11:32:31.581Z build.artifact=我的应用程序 build.group=org.mycompany build.name=我的应用程序 build.version=开发

当从 IDEA

构建项目时,此开发版本将自动复制到 IDEA /out/production/resources 目录
  1. bootBuildInfo 任务和 processResources 任务之间创建一个任务依赖关系,以确保 Spring 启动插件将使用 up-to-date 构建应用程序 jar 时的版本:

    bootBuildInfo.mustRunAfter 进程资源

这样,SpringBoot gradle 插件将覆盖 processResources 任务从源复制的文件及其 auto-generated up-to-date 文件。

编辑 2020-10

正如 Dmitry 在下面的评论中警告的那样,此解决方案将破坏 Gradle 增量构建,因为 processResourcesbootBuildInfo 任务共享相同的输出文件 build-info.properties。为了避免这种情况,我们可以在 processResources 中添加排除项来过滤掉这个文件,当我们检测到任务图包含 bootBuildInfo 任务

project.gradle.taskGraph.whenReady {
    if (it.allTasks.any {it.name == "bootBuildInfo"}) {
        processResources {
            exclude("META-INF/build-info.properties")
        }
    }
}

对于在 IntelliJ IDEA Community Edition 中遇到此问题的任何其他人(@Andrey 所说的选项不存在),您只需在启动前添加一个 Run Maven Goal。这将执行插件的目标:spring-boot:build-info before build and 运行