Question

Can I do something like working-dir="file:${user.home}/some-directory" within my .properties file? I am using ResourceBundle to load configuration from a .properties file and I would to inherit a system property key such as user.home for my working-dir property. It would be nice to be able to do this since I can have different versions of the .properties in resource directory of the source package and test package respectively. I want to define different values for working-dir for my production and testing environment.

Was it helpful?

Solution

You cannot do that directly, however you can parse your properties in your code and programatically expand the variables, e.g.

  • Search for the pattern ${varname} in your property
  • Get the value of varname from the system properties
  • Replace ${varname} with the value of system property varname

Here is a simple implementation of the above:

String property = "file:${user.home}/some-directory";

StringBuffer sb = new StringBuffer();
Pattern pattern = Pattern.compile("\\$\\{(.+)\\}");
Matcher matcher = pattern.matcher(property);
while (matcher.find())
{
    String key = matcher.group(1);
    String val = System.getProperty(key);
    if (val != null)
    {
        matcher.appendReplacement(sb, Matcher.quoteReplacement(val));
    }
}
matcher.appendTail(sb);
System.out.println(sb.toString());

OTHER TIPS

Just tried Apache commons configuration's variable interpolation and it works perfect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top