简体   繁体   English

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

[英]Loading environment properties using Spring profiles

I am working in Spring, Java, Ant web application. 我正在使用Spring, Java, Ant Web应用程序。 I am using Spring profiling to load properties based on the enironment. 我正在使用Spring性能分析来加载基于环境的属性。 Below is the sample 下面是示例

@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{

}

In web.xml , we can give the profile web.xml中 ,我们可以提供配置文件

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

Now, my query is for every environment i need to create a separate Java class. 现在,我的查询针对需要创建单独的Java类的每种环境。

Question: Is it possible to have only one class like providing profile name as some binding parameter like @Profile({profile}) . 问题:是否可能只有一个类,例如提供配置文件名称作为某些绑定参数,例如@Profile({profile})

Also, let me know if there is other better option available to achieve the same. 另外,请告诉我是否还有其他更好的选择可实现相同目标。

There can be multiple profiles active at one time, so there is no single property to obtain the active profile. 一次可能有多个配置文件处于活动状态,因此没有单个属性可以获取活动配置文件。 A general solution is to create an ApplicationContextInitializer which based on the active profiles loads additional configuration files. 一个通用的解决方案是创建一个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);
               }
            }
        }
    }
}

Something like that should do the trick (might contain errors as I typed it from the top of my head). 诸如此类的事情应该可以解决(在我从头顶输入时可能包含错误)。

Now in your web.xml include a context parameter named contextInitializerClasses and give it the name of your initializer. 现在,在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