可以通过属性文件设置Spring的活动配置文件吗?

7

我希望能够从属性文件中读取活动配置文件,以便在基于Spring MVC的Web应用程序中为不同的环境(如dev、prod等)配置不同的配置文件。我知道可以通过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,按优先级(如果存在override.properties,则首先加载它,否则加载application.properties),加载这些属性文件并在context.getEnvironment()中设置值。是否有更好的方法从属性文件中解决这个问题?


2
通常更明智的做法是设置一个操作系统环境变量并将其传递给Spring。这样您就可以将一个WAR部署到不同的服务器上,而无需进行其他操作,它们将基于该环境变量值表现出不同的行为。 - Neil McGuigan
1
可能是如何在Spring中使用application.properties设置配置文件?的重复问题。 - Bond - Java Bond
请包含代码片段以展示如何使用PropertiesConfigurer设置配置文件。 - UserF40
1个回答

3

一种解决方法是手动读取指定配置文件的属性,而不使用Spring,并在上下文初始化时设置配置文件:

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();
}

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