我正在尝试使用来自系统属性的路径在 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/