繁体   English   中英

使用Spring配置文件加载环境属性

[英]Loading environment properties using Spring profiles

我正在使用Spring, Java, Ant Web应用程序。 我正在使用Spring性能分析来加载基于环境的属性。 下面是示例

@Profile("dev")
@Component
@PropertySource("classpath:dev.properties")
public class DevPropertiesConfig{

}
@Profile("qa")
@Component
@PropertySource("classpath:qa.properties")
public class TestPropertiesConfig {

}

@Profile("live")
@Component
@PropertySource("classpath:live.properties")
public class LivePropertiesConfig{

}

web.xml中 ,我们可以提供配置文件

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>

现在,我的查询针对需要创建单独的Java类的每种环境。

问题:是否可能只有一个类,例如提供配置文件名称作为某些绑定参数,例如@Profile({profile})

另外,请告诉我是否还有其他更好的选择可实现相同目标。

一次可能有多个配置文件处于活动状态,因此没有单个属性可以获取活动配置文件。 一个通用的解决方案是创建一个ApplicationContextInitializer ,它基于活动的配置文件加载其他配置文件。

public class ProfileConfigurationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    public void initialize(final ConfigurableApplicationContext ctx) {
        ConfigurableEnvironment env = ctg.getEnvironment();
        String[] profiles = env.getActiveProfiles();
        if (!ArrayUtils.isEmpty(profiles)) {
            MutablePropertySources mps = env.getPropertySources();
            for (String profile : profiles) {
               Resource resource = new ClassPathResource(profile+".properties");
               if (resource.exists() ) {
                   mps.addLast(profile + "-properties", new ResourcePropertySource(resource);
               }
            }
        }
    }
}

诸如此类的事情应该可以解决(在我从头顶输入时可能包含错误)。

现在,在web.xml包含一个名为contextInitializerClasses的上下文参数,并为其指定初始化程序的名称。

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>your.package.ProfileConfigurationInitializer</param-value>
</context-param>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM