使用 Spring 配置文件加载环境属性 [英] Loading environment properties using Spring profiles

查看:125
本文介绍了使用 Spring 配置文件加载环境属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Spring、Java、Ant 网络应用程序中工作.我正在使用 Spring 分析来加载基于环境的属性.以下是样本

I am working in Spring, Java, Ant web application. I am using Spring profiling to load properties based on the enironment. 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{

}

web.xml中,我们可以给出配置文件

In web.xml, we can give the profile

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

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

Now, my query is for every environment i need to create a separate Java class.

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

Question: Is it possible to have only one class like providing profile name as some binding parameter like @Profile({profile}).

另外,如果有其他更好的选择可以实现相同的目标,请告诉我.

Also, let me know if there is other better option available to achieve the same.

推荐答案

一次可以有多个活动配置文件,因此没有单个属性可以获取活动配置文件.一般的解决方案是创建一个 ApplicationContextInitializer,它基于活动配置文件加载额外的配置文件.

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.

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).

现在在您的 web.xml 中包含一个名为 contextInitializerClasses 的上下文参数,并为其指定初始值设定项的名称.

Now in your web.xml include a context parameter named contextInitializerClasses and give it the name of your initializer.

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

这篇关于使用 Spring 配置文件加载环境属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆