Java和YAML:如何解析多个yaml文档并将它们合并到一个YAML表示中?

时间:2014-10-13 17:03:27

标签: java merge yaml snakeyaml

假设我有一个文件defaults.yaml

pool:
  idleConnectionTestPeriodSeconds: 30
  idleMaxAgeInMinutes: 60
  partitionCount: 4
  acquireIncrement: 5
  username: dev
  password: dev_password

和另一个文件production.yaml

pool:
  username: prod
  password: prod_password

在运行时,如何读取这两个文件并将它们合并为一个,以便应用程序“看到”以下内容?

pool:
  idleConnectionTestPeriodSeconds: 30
  idleMaxAgeInMinutes: 60
  partitionCount: 4
  acquireIncrement: 5
  username: prod
  password: prod_password

这可能与SnakeYAML有关吗?还有其他工具吗?

我知道一个选项是在地图中读取多个文件,然后自己合并,将合并渲染到一个临时文件然后读取,但这是一个重量级的解决方案。现有工具可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Jackson,关键是使用 ObjectMapper.readerForUpdating()并使用 @JsonMerge 注释字段(否则下一个对象中所有缺少的字段将覆盖旧的):

行家:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.9</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.9.9</version>
    </dependency>

代码:

public class TestJackson {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        MyConfig myConfig = new MyConfig();
        ObjectReader objectReader = mapper.readerForUpdating(myConfig);
        objectReader.readValue(new File("misc/a.yaml"));
        objectReader.readValue(new File("misc/b.yaml"));
        System.out.println(myConfig);
    }

    @Data
    public static class MyConfig {
        @JsonMerge
        private Pool pool;
    }

    @Data
    public static class Pool {
        private Integer idleConnectionTestPeriodSeconds;
        private Integer idleMaxAgeInMinutes;
        private Integer partitionCount;
        private Integer acquireIncrement;
        private String username;
        private String password;
    }
}