0

我在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中,我们可以给出配置文件

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

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

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

另外,让我知道是否有其他更好的选择可以实现相同的目标。

4

1 回答 1

0

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