首页 > 解决方案 > 如何在构建 bootJar 时在 Spring Boot 上设置活动配置文件?

问题描述

如何仅为通过调用 bootJar 任务构建的可执行文件(jar)设置配置文件?理想情况下,它会覆盖(或添加)jar 内 application.properties 中的属性或类似的东西。

标签: spring-boot

解决方案


我希望他正在努力做我们现在的样子。在 Maven 中,可以按照以下方式做一些事情:

<profile>
  <id>openshift</id>
  <properties>
    <activatedProperties>openshift</activatedProperties>
  </properties>
</profile>

可用于将@activatedProperties@application.properties 中的替换为例如 openshift。如果是这种情况,我们通过修改 build.gradle 来解决它,如下所示:

import org.apache.tools.ant.filters.ReplaceTokens

# whatever you have here

def springProfile = project.hasProperty("profile") ? profile : ""
bootRun {
    systemProperties["spring.profiles.active"] = springProfile
}

processResources {
    with copySpec {
        from "src/main/resources/"
        filter(ReplaceTokens, tokens: ["activatedProperties": springProfile])
    }
}

并且在 application.properties 中有:

spring.profiles.active=@activatedProperties@

但是,我想指出,我们认为这是一个临时的黑客攻击。构建脚本不应该修改文件,即使它仅限于资源文件。更正确的方法是在单独的位置使用模板并将其输出到资源。或者更好(这是我们将在适当的时候做的),修复部署设置,所以它应该是部署配置的一部分。


推荐阅读