简体   繁体   English

使用 Java 中的占位符解析 yaml

[英]Parse a yaml with placeholder in Java

I have a yaml file which consist of placeholders to be taken from environment variable.我有一个 yaml 文件,其中包含要从环境变量中获取的占位符。 I want to parse it to a custom class.我想将其解析为自定义 class。 Currently I am using snakeyaml library to parse it and its populating the bean correctly, how can I resolve environment variables using snakeyaml or any other library in Java.目前我正在使用snakeyaml 库来解析它并正确填充bean,如何使用snakeyaml 或Java 中的任何其他库来解析环境变量。

datasource:
  url: {url_environment_variable}
  foo: bar
  username: {user_name_environment_variable}
  password: {password_environment_variable}

@Getter
@Setter
public class DataSource {
private String url;
private String foo;
private String username;
private String password;
}

Parsing code below下面解析代码

Constructor c = new Constructor(MyDataSource.class);
Yaml yaml = new Yaml(c);
MyDataSource myData = yaml.loadAs(inputStream, MyDataSource.class);

The problem is I am yet to find a way to resolve placeholders.问题是我还没有找到解决占位符的方法。 People were able to solve it using python and is available in question - How to replace environment variable value in yaml file to be parsed using python script人们能够使用 python 解决它,并且有问题 - How to replace environment variable value in yaml file to be parsed using python script

How can I do the same in Java.我怎样才能在 Java 中做同样的事情。 I can add a new dependency if required.如果需要,我可以添加新的依赖项。 PS - It's not a Spring Boot Project so standard Spring placeholder replacements can not be used. PS - 它不是 Spring 引导项目,因此不能使用标准 Spring 占位符替换。

The easiest way would be to do it in two passes.最简单的方法是分两次完成。 First deserialize into MyDataSource as you're doing already.首先反序列化为MyDataSource ,就像你已经在做的那样。 Then use reflection to iterate over all fields of the instance, and if the value starts with a curly brace and ends with one, extract the key, and get the value from System.getenv map.然后使用反射遍历实例的所有字段,如果值以花括号开头并以1结尾,则提取键,并从System.getenv map中获取值。 See this answer for code.请参阅此答案以获取代码。

If you want to do it in one pass, then you need to use the snakeyaml event-driver parser.如果你想一次性完成,那么你需要使用snakeyaml 事件驱动解析器。 For every key, you resolve the value as described above, and then based on the key name, set the corresponding field in the MyDataSource class, either using reflection, or simple if-else.对于每个键,您按照上述方法解析值,然后根据键名称,使用反射或简单的 if-else 设置MyDataSource中的相应字段。 For an example of the event-driven parser, see this class ;有关事件驱动解析器的示例,请参阅此 class it's not Java, it's Kotlin, but it may be the only JVM language example you'll find.它不是 Java,而是 Kotlin,但它可能是您能找到的唯一 JVM 语言示例。

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

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