简体   繁体   中英

Typesafe config - Setting placeholder values from a program

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.

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"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM