【问题标题】:Loading environment properties using Spring profiles使用 Spring 配置文件加载环境属性
【发布时间】:2015-11-22 21:33:25
【问题描述】:

我在Spring, Java, Ant 网络应用程序中工作。我正在使用 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中,我们可以给出profile

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

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

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

另外,如果有其他更好的选择可以达到同样的效果,请告诉我。

【问题讨论】:

  • 是的,这是可能的,而且你做得对。
  • 代替这个使用ApplicationContextInitializer,它基于活动的配置文件添加一个指向该配置文件的ResourcePropertySource。这也是 Spring Boot(或多或少)所做的。
  • 有关@M.Deinum 答案的详细示例,请参阅此SO answer。
  • 我已经删除了我的解决方案,因为它是硬编码配置文件名称。您可以在上面的 SO 答案链接中参考解决方案。
  • @M.Deinum,是否可以创建单个 bean 来加载属性文件。由于 OP 必须使用 3 个单独的类。

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


【解决方案1】:

一次可以有多个处于活动状态的配置文件,因此没有单一的属性可以获取活动的配置文件。一个通用的解决方案是创建一个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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-16
    • 2015-02-18
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2014-06-30
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多