简体   繁体   English

Typesafe配置-从程序设置占位符值

[英]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? 有什么方法可以使用源代码填充占位符来动态更改Typesafe配置文件的字段?

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. 正如HOCON文档中所讨论的,以及在先前的StackOverflow问题中提到的那样 ,可以使用环境变量和系统属性来实现这一目标。

Is it possible to also do the same thing directly from a program? 是否可以直接从程序中做同样的事情? For instance, in Java , having a class Constants like 例如,在Java ,具有类Constants

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. HOCON允许将Java和执行代码集成到配置文件中,但是显然无法从集成的Java代码中设置配置占位符。

You can resolve placeholders by calling resolve(...) with a config of resolved placeholders on an instance of Config . 您可以通过在Config实例上使用带有已解析占位符的配置调用resolve(...)来解析占位符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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