使用 bootWar 设置活动 spring 配置文件

Set active spring profile with bootWar

我正在尝试在构建 WAR 文件时设置活动的 spring 配置文件。我正在用 gradle bootWar

构建 WAR 文件

我设法找到了适用于 gradle bootRun -Pprofiles=prod

的解决方案
bootRun {
  if (project.hasProperty('profiles')) {
    environment SPRING_PROFILES_ACTIVE: profiles
  }
}

但是

bootWar {
  if (project.hasProperty('profiles')) {
    environment SPRING_PROFILES_ACTIVE: profiles
  }
}

给我这个错误

Could not find method environment() for arguments [{SPRING_PROFILES_ACTIVE=staging}] on task ':bootWar' of type org.springframework.boot.gradle.tasks.bundling.BootWar.

如何让它适用于 WAR 个文件?

(链接指的是一个演示项目,我在其中做的和您现在正在尝试做的一样,但有一些额外的复杂性,请先阅读 属性 等,然后设置不同的配置文件处于活动状态:developmenttestingproduction 和其他一些 SO 帖子)


假设我们要将活动配置文件设置为 production

build.gradle 中,您可以像这样创建一个 task which writes the property spring.profiles.active using the ant.propertyfile

task setProductionConfig() {
    group = "other"
    description = "Sets the environment for production mode"
    doFirst {
        /*
           notice the file location ("./build/resources/main/application.properties"),
           it refers to the file processed and already in the build folder, ready
           to be packed, if you use a different folder from `build`, put yours
           here
        */
        ant.propertyfile(file: "./build/resources/main/application.properties") {
            entry(key: "spring.profiles.active", value: "production")
        }
    }
    doLast {
        // maybe put some notifications in console here
    }
}

然后你告诉 bootWar 任务它取决于我们之前做的任务 this:

bootWar {
    dependsOn setProductionConfig
}