【问题标题】:How to overwrite values loaded from properties file if new value is provided in command line如果在命令行中提供了新值,如何覆盖从属性文件加载的值
【发布时间】:2017-07-27 16:07:32
【问题描述】:

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

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 将是解决的问题。

【问题讨论】:

    标签: java command-line properties


    【解决方案1】:

    加载属性文件后,我执行以下操作:

    for (String propertyName : properties.stringPropertyNames()) {
        String systemPropertyValue = System.getProperty(propertyName);
    
        if (systemPropertyValue != null) {
            properties.setProperty(propertyName, systemPropertyValue);
        }
    }
    

    这通过使用相应的系统属性值(如果存在)覆盖属性文件中的值,为您提供所需的行为。

    【讨论】:

    • 谢谢!它做了我需要的。你会说这通常是处理属性的好方法吗?我的意思是从文件中加载它们,然后应用您的解决方案来查找是否应该覆盖它们中的任何一个?
    • 只要你只需要初始化一次,我真的想不出更优雅的方法。如果系统属性可以在运行时更改,则每次获取属性时都必须检查以查看是否存在相应的系统属性。不过我从来没有遇到过这种情况。应用程序和框架似乎依赖于系统属性在启动后不可变这一事实。
    猜你喜欢
    • 2013-03-06
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2012-07-06
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多