Eugene S Eugene S - 3 years ago 123
Java Question

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:

Q1

Q2

however my case seems to be slightly different.

So I have a

config.properties
file that is being loaded by
ConfigurationGetter
class like this:

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:

keyName=true


and I also run the code like this:

mvn test -DkeyName=false


then
false
will be the one resolved.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download