如何从环境变量中添加一个活动的Spring配置文件?

10

目前为止,我在我的~/.bash_profile中设置了以下环境变量:

export SPRING_PROFILES_ACTIVE=local

我设置了活动的 spring 配置文件。但是现在,我想将本地配置文件添加application.properties 中定义的其他配置文件中而不是替换它们。

Spring Boot 文档中,有一个关于添加活动配置文件的部分,但我没有看到有关从环境变量添加活动配置文件的内容。

我尝试设置 SPRING_PROFILES_INCLUDE 环境变量,但这没有任何效果。

如何做到这一点?

P.S.:我正在使用 Spring Boot 1.4.2。


你尝试过使用ConfigurableEnvironment吗?http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/ConfigurableEnvironment.html - SeaBiscuit
1
不,我没有,但我更喜欢使用像Olszewski这样的解决方案。 - Ortomala Lokni
5个回答

13

你链接的文档中的下一句话是:

  

有时候,拥有针对特定环境的属性可以增加活动配置文件而不是替换它们。 spring.profiles.include 属性可用于无条件添加活动配置文件。

因此,您可以使用命令行参数启动应用程序:

-Dspring.profiles.include=${SPRING_PROFILES_INCLUDE}

11

使用默认添加配置文件

您可以在application.properties文件中使用表达式来定义自己的环境变量,并将其放置在已定义的配置文件旁边。例如,如果您的当前文件如下所示:

spring.profiles.active=profile1,profile2

使用自定义环境变量,它将变成:

spring.profiles.active=profile1,profile2,${ADDITIONAL_APP_PROFILES:local}

这里的 ADDITIONAL_APP_PROFILES 是您设置的环境变量的名称,代替了 SPRING_PROFILES_ACTIVE

如果在当前环境中未设置该变量,则使用值为 local。在这种情况下,将激活名为 local 的配置文件。如果您没有设置默认值且环境变量不存在,则整个表达式将用作活动配置文件的名称。

不使用默认附加配置文件

如果您希望避免激活默认配置文件,则可以删除变量表达式前的占位符值和逗号:

spring.profiles.active=profile1,profile2${ADDITIONAL_APP_PROFILES}

但在这种情况下,当前环境中设置的变量必须以逗号开头:

export ADDITIONAL_APP_PROFILES=,local

1
这是一个示例,演示如何从系统环境变量或JVM参数中添加可编程的额外活动配置文件。
@Configuration
public class ApplicationInitializer implements WebApplicationInitializer, ApplicationContextInitializer<ConfigurableWebApplicationContext> {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("contextInitializerClasses", this.getClass().getCanonicalName());
    }

    @Override
    public void initialize(ConfigurableWebApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        environment.addActiveProfile(System.getProperty("myProperty"));
        environment.addActiveProfile(System.getEnv("myProperty"));
    }
}

0

这里不是Spring的方式,但在某些情况下也可能很有用。

public static void main(String[] args) {
    System.setProperty("spring.profiles.active", "local");
    SpringApplication.run(MainApplication.class, args);
}

-2

抱歉,我只理解你帖子的一半。能否请您重新表述一下? - Peter Wippermann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接