java - 如果在命令行中提供了新值,如何覆盖从属性文件加载的值

标签 java command-line properties

有趣的是,我发现了 2 个标题相似但几乎相同的问题:

Q1

Q2

但是我的情况似乎略有不同。

所以我有一个 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/

相关文章:

java - lzo 编解码器 b/w python 和 java 的区别

svn - 颠覆 : commit only modified files

xml - 在 actionscript 中,检查 xml 节点属性是否存在的最佳方法是什么?

java - 属性文件中的属性未更改

c# - Visual Basic 默认属性与 C# 属性

java - 单击十字时在系统托盘中添加 jframe,而不是在最小化按钮的情况下添加 jframe

android - 由于 java 不正确,无法构建 android

java - 我在 android 上使用 java 时遇到异常 (java.lang.NoClassDefFoundError),为什么?

windows - For 循环运行两次,但仅针对第一个文件

java - 在 while 循环 shell 中运行 Java