Reputation: 175
I am working with Java and spring boot apps. I have a property file which needs to be added as environmental variables for a docker image at run time. Some of the properties are filtered through the existing Environment when they are used via placeholders as below.
app.name=MyApp
app.description=${app.name} is a Spring Boot application
I am writing a sample java file to read this property file and create a map object with some filtered properties. In this process how can I replace the placeholders with the actual property values?
I have tried looking for a key and replacing using getProperty
method. But I would like to avoid looking up hard coded property key names in order to avoid maintenance difficulties.
Thanks in advance.
Upvotes: 3
Views: 6967
Reputation: 6329
I would create a new Properties
descendant, with a method that gets a property value, and replaces any references, if any.
Something like this:
class MyProperties extends Properties
{
// Constructors, as needed
private Pettern p = Pattern.compile("\\$\\{([^}]+)\\}");
public String getString(final String key)
{
final String value = getProperty(key);
if (null == value)
return null;
final StringBuffer result = new StringBuffer();
final Matcher m = p.matcher(value);
while (m.find())
{
final String refKey = m.group(1);
final String refValue = getProperty(refKey);
m.appendReplacement(result, null == refValue ? refKey : refValue);
}
m.appendTail(result);
return result.toString();
}
}
Upvotes: 2
Reputation:
Replace the named token with numbered token and use the MessageFormat class of Java SE. It allows you to do exactly what you ask for.
Assuming props contains all the properties loaded from your file.
MessageFormat.format((String) props.get("app.description"),((String) props.get("app.name"));
Here your property shall be :
app.description={0} is a Spring Boot application
Else you will need to write a custom
Upvotes: 5