apache PropertiesConfiguration 不解析占位符

apache PropertiesConfiguration doesn't resolve placeholders

假设我有以下两个配置文件:

文件 1:

key1 = ${common.key1}
key2 = ${common.key2}

文件 2:

common.key1 = value1
common.key2 = value2

我有以下代码:

import org.apache.commons.configuration.PropertiesConfiguration;
...
PropertiesConfiguration newConfig = new PropertiesConfiguration();
File configFile1 = new File("...paht to file 1");
File configFile2 = new File("...path to file 2");
newConfig.setDelimiterParsingDisabled(true);
newConfig.load(configFile2);
newConfig.load(configFile1);

Iterator<String> props = newConfig.getKeys();
while (props.hasNext()) {
    String propName = props.next();
    String propValue = newConfig.getProperty(propName).toString();
    System.out.println(propName + " = " + propValue);
}

我有以下输出:

common.key1 = value1
common.key2 = value2
key1 = ${common.key1}
key2 = ${common.key2}

为什么占位符没有解析?

请参阅文档中的 this page,其中说:

Below is some more information related to variable interpolation users should be aware of:

  • ...

  • Variable interpolation is done by all property access methods. One exception is the generic getProperty() method which returns the raw property value.

这正是您在代码中使用的内容。

API docs of getProperty() 也提到了这一点:

Gets a property from the configuration. ... On this level variable substitution is not yet performed.

使用 PropertiesConfiguration 中可用的其他方法来获取实际的内插值。例如,在 PropertiesConfiguration 上调用 getProperties() 将其转换为 java.util.Properties 对象并对其进行迭代。

也可以通过如下所示的占位符替换以通用方式使用它:

config.get(Object.class, propName);

getProperty 方法不同,带有 Object.class 参数的 get 方法将 return 原始 class 的值与变量插值。