Dynamic Placeholder Substitution in Properties in Java

How to set placeholder values in properties file in spring

Use MessageFormat.format(String pattern, Object ... arguments). It accepts an array in second parameter, which will replace 0, 1 , 2 ... sequentially.

MessageFormat.format(env.getProperty("app.not.found"), obj)

obj will replace {0} in your string.

Spring putting dynamically generated values into placeholders

By runtime, do you mean dynamically for each message?

In that case, no, because the clientId is used while establishing the connection, which is done once (or when the connection to the server is lost).

If you mean to provide a dynamic value programmatically when the application context initializes, then, yes, the Spring Expression Language is the solution.

For example, #{myBean.myProperty} will call the getMyProperty() method on a bean myBean and #{myBean.someMethod()} will invoke someMethod().

Also see the dynamic-ftp sample, which uses placeholders at runtime by creating a new outbound adapter on demand using property placeholders, in a child application context.

Replace placeholders in property file with VM argument passed (-D params) using spring 4

Read your .properties file in a Properties object and then replace the placeholders by the values passed via VM arguments:

public static boolean replaceVariables(Properties properties) {
boolean changed = false;
for (Entry<Object, Object> entry : properties.entrySet()) {
if (entry.getValue() instanceof String) {
String value = (String) entry.getValue();
value = value.trim();
if (value.startsWith("${") && value.endsWith("}")) {
value = System.getProperty(value.substring(2, value.length() - 1));
if (value == null)
entry.setValue("");
else
entry.setValue(value);
changed = true;
}
}
}
return changed;
}


Related Topics



Leave a reply



Submit