有趣的是,我发现了 2 个标题相似但几乎相同的问题:
但是我的情况似乎略有不同。
所以我有一个 config.properties
文件,它由 ConfigurationGetter
类加载,如下所示:
public class ConfigurationGetter {
Properties prop = new Properties();
InputStream inputStream = null;
public Properties getPropValues() throws IOException {
try {
String fileName = "config.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + fileName + "' not found in the classpath");
}
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
inputStream.close();
}
return prop;
}
然后我像这样在另一个类中实例化这个类:
ConfigurationGetter config = new ConfigurationGetter();
props = config.getPropValues();
然后我可以像这样按键提取属性:
props.getProperty("keyName")
如果我通过命令行提供它,我想做的是覆盖我从属性文件中获得的这个值。例如,如果我的 config.properties
中有这样一行,我按上面的解释加载了它:
keyName=true
我也像这样运行代码:
mvn test -DkeyName=false
然后 false
将被解析。
最佳答案
加载属性文件后,我执行以下操作:
for (String propertyName : properties.stringPropertyNames()) {
String systemPropertyValue = System.getProperty(propertyName);
if (systemPropertyValue != null) {
properties.setProperty(propertyName, systemPropertyValue);
}
}
这通过使用相应的系统属性值(如果存在)覆盖属性文件中的值来为您提供所需的行为。
关于java - 如果在命令行中提供了新值,如何覆盖从属性文件加载的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45344591/