Reputation: 19905
Is there any way for dynamically changing the fields of a Typesafe config file, using source code to populate placeholders?
For example, assume the following simple configuration statement
{
values {
string1: ${name1}
string2: ${name2}
string3: ${name3}
string4: ${name4}
}
}
As discussed in HOCON documentation and mentioned in an earlier StackOverflow question, one can use environmental variables and system properties to achieve this.
Is it possible to also do the same thing directly from a program? For instance, in Java
, having a class Constants
like
public class Constants
{
public static final String name1 = "A";
public static final String name2 = "B";
public static final String name3 = "C";
public static final String name4 = "D";
}
and populating the configuration fields from that class?
HOCON
allows integrating Java
and executing code in the config file but apparently there is no way to set config placeholders from within the integrated Java
code.
Upvotes: 2
Views: 3886
Reputation: 2253
You can resolve placeholders by calling resolve(...)
with a config of resolved placeholders on an instance of Config
.
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.Config;
public class ConfigOverrideFromCode {
static public void main(String[] args) {
String config = "system.administrator = ${who-knows}";
Config original = ConfigFactory
.parseString(config)
.resolveWith(ConfigFactory.parseString("who-knows = jon"));
System.out.println(original.getString("system.administrator"));
}
}
Upvotes: 5