【问题标题】:Loading property file from system properties with default path in Spring context在 Spring 上下文中使用默认路径从系统属性加载属性文件
【发布时间】:2015-06-04 09:45:03
【问题描述】:

我正在尝试在我的 Spring 上下文中加载一个属性文件(位于战争之外),其路径来自系统属性。

如果该系统属性不存在或找不到路径,我想回退到包含在我的 .war 中的默认属性文件。

这是我的 applicationContext.xml 的特定部分

<context:property-placeholder ignore-resource-not-found="true" ignore-unresolvable="true" location="file:${config.dir}/config/server.properties"/>
<context:property-placeholder ignore-resource-not-found="false" location="classpath:config/server.properties"/>

问题是当在系统属性中找不到 config.dir 时,会抛出一个异常,说明解析器找不到该属性。

即使它会解决,我很确定第二行会使得在参数中给出的文件中加载的属性被默认文件中的属性替换,这与我的相反想做。

我正在使用 Spring 4.x,仅配置 xml。

有没有可能做我想做的事? 我知道基于 Java 的配置的 @Conditional,但我只能使用 xml 方式来响应项目的标准。

【问题讨论】:

    标签: spring


    【解决方案1】:

    不要使用 2 个占位符,使用单个占位符,location 属性采用 , 分隔的文件列表来加载。

    <context:property-placeholder ignore-resource-not-found="true" location="file:${config.dir}/config/server.properties,classpath:config/server.properties"/>
    

    但是config.dirproperty 必须可用,否则加载会爆炸。

    另一种解决方案是使用ApplicationContextInitializer 并根据config.dir 属性加载或不加载附加文件的可用性。

    public class ConfigInitializer implements ApplicationContextInitializer {
    
        public void initialize(ConfigurableApplicationContext applicationContext) {
            ConfigurableEnvironment env = applicationContext.getEnvironment();
            MutablePropertySources mps = env.getPropertySources();
    
            mps.addLast(new ResourcePropertySource("server.properties", "classpath:config/server.properties"));
    
            if (env.containsProperty("config.dir")) {
                String configFile = env.getProperty("config.dir")+"/config/server.properties";
                Resource resource = applicationContext.getResource(configFile);
                if (resource.exists() ) {
                    mps.addBefore("server.properties", new ResourcePropertySource(resource));
                }
            }
        }
    }
    

    现在您只需要一个空的 &lt;context:property-placeholder /&gt; 元素。

    额外的好处是您可以在默认属性中指定默认的config.dir,并使其被系统或环境属性覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2019-03-04
      • 2011-02-16
      • 2020-06-05
      • 1970-01-01
      相关资源
      最近更新 更多