【问题标题】:Can the Spring active profiles be set through a property file?可以通过属性文件设置 Spring 活动配置文件吗?
【发布时间】:2015-11-05 17:55:44
【问题描述】:

我希望能够从属性文件中读取活动配置文件,以便可以在基于 Spring MVC 的 Web 应用程序中使用不同的配置文件配置不同的环境(开发、生产等)。我知道可以通过 JVM 参数或系统属性设置活动配置文件。但我想通过一个属性文件来代替。关键是我不知道静态的活动配置文件,而是想从属性文件中读取它。看起来这是不可能的。例如,如果我在 application.properties 中有“spring.profiles.active=dev”,并允许它在 override.properties 中被覆盖,如下所示:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:/application.properties</value>
            <value>file:/overrides.properties</value>
        </list>
    </property>
</bean> 

没有在环境中拾取配置文件。我猜这是因为在 bean 初始化之前正在检查活动配置文件,因此不尊重在属性文件中设置的属性。我看到的唯一其他选项是实现一个 ApplicationContextInitializer,它将按优先级顺序加载这些属性文件(如果存在,则首先覆盖.properties,否则为 application.properties)并在 context.getEnvironment() 中设置值。有没有更好的方法从属性文件中做到这一点?

【问题讨论】:

  • 设置一个O/S env var并将其传递给spring通常更聪明。这样你就可以将一场战争部署到不同的服务器上,而不是其他任何东西,它们的行为会根据该环境变量值而有所不同
  • 包含代码片段以显示配置文件是如何使用占位符设置到 propertiesconfigurer 的。

标签: spring spring-mvc spring-profiles spring-properties


【解决方案1】:

一种解决方案是“手动”读取具有指定配置文件的必要属性文件 - 没有弹簧 - 并在上下文初始化时设置配置文件:

1) 编写简单的属性加载器:

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

public class PropertiesLoader
{
    private static Properties props;

    public static String getActiveProfile()
    {
        if (props == null)
        {
            props = initProperties();
        }
        return props.getProperty("profile");
    }

    private static Properties initProperties()
    {
        String propertiesFile = "app.properties";
        try (Reader in = new FileReader(propertiesFile))
        {
            props = new Properties();
            props.load(in);
        }
        catch (IOException e)
        {
            System.out.println("Error while reading properties file: " + e.getMessage());
            return null;
        }
        return props;
    }
}

2) 从属性文件中读取配置文件并在 Spring 容器初始化期间对其进行设置(基于 Java 的配置示例):

public static void main(String[] args)
{
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.getEnvironment().setActiveProfiles(PropertiesLoader.getActiveProfile());
    ctx.register(AppConfig.class);
    ctx.refresh();

    // you application is running ...

    ctx.close();
}

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 2012-01-25
    • 2022-08-16
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2012-02-17
    相关资源
    最近更新 更多