spring - 在 Spring 上下文中使用默认路径从系统属性加载属性文件

标签 spring

我正在尝试使用来自系统属性的路径在 Spring 上下文中加载属性文件(位于 war 之外)。

如果该系统属性不存在或未找到路径,我想回退到 .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 方式来响应项目的条件。

最佳答案

不要使用 2 个占位符,使用一个占位符,即 location属性需要 ,要加载的分隔文件列表。

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

但是config.dir属性必须可用,否则加载将会爆炸。

另一个解决方案是使用 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));
            }
        }
    }
}

现在你只需要一个空的<context:property-placeholder />元素。

额外的优点是您可以指定默认值 config.dir在您的默认属性中,并由系统或环境属性覆盖它。

关于spring - 在 Spring 上下文中使用默认路径从系统属性加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30640453/

相关文章:

java - 我可以仅通过 xml 完全不使用注释来使用 Spring 吗?

java - Spring AOP - 我想将切入点应用到库中的类

spring - 仅使用一个存储库保存请求来保存一个对象和一个嵌套对象

Spring Security 和无状态 Restful 服务

java - 我应该如何编写我的 JSP 文件——Java、JSTL 或其他?

java - StompBrokerRelayMessageHandler - 许多日志错误

java - 无法将类型 'java.lang.String' 的值转换为所需类型 'java.lang.Integer' 在 jpa spring 中

java - IncorrectResultSizeDataAccessException - 尝试简单地获取最新的行

java - 动态切换数据源

java - 如何使用Spring编写注解触发的方法拦截器?