[英]How to overwrite values loaded from properties file if new value is provided in command line
Funny enough there are 2 almost identical questions with a similar title that I found: 有趣的是,我发现了2个几乎相同且标题相似的问题:
however my case seems to be slightly different. 但是我的情况似乎有些不同。
So I have a config.properties
file that is being loaded by ConfigurationGetter
class like this: 所以我有一个由
ConfigurationGetter
类加载的config.properties
文件,如下所示:
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;
}
Then I instantiate this class in another class like this: 然后,在另一个这样的类中实例化该类:
ConfigurationGetter config = new ConfigurationGetter();
props = config.getPropValues();
And then I can extract the properties by key like this: 然后我可以像这样通过键提取属性:
props.getProperty("keyName")
Whet I want to do is to overwrite this value I get from properties file if I provide it via command line. 如果我是通过命令行提供的,我想做的就是覆盖从属性文件中获得的该值。 For example, if I have a line like this in my
config.properties
that I loaded as explained above: 例如,如果在我的
config.properties
中有一条如上所述的行,则如上所述进行加载:
keyName=true
and I also run the code like this: 并且我还运行如下代码:
mvn test -DkeyName=false
then false
will be the one resolved. 那么
false
将被解决。
After loading the properties file, I do the following: 加载属性文件后,请执行以下操作:
for (String propertyName : properties.stringPropertyNames()) {
String systemPropertyValue = System.getProperty(propertyName);
if (systemPropertyValue != null) {
properties.setProperty(propertyName, systemPropertyValue);
}
}
This gives you the behavior you want by overriding the value from the property file with the corresponding system property value if it is present. 通过使用相应的系统属性值(如果存在)覆盖属性文件中的值,可以提供所需的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.