假设我有一个文件,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 这可能吗?还有其他工具吗?
我知道一个选择是将多个文件作为 map 读取,然后自己合并它们,将合并呈现为单个临时文件,然后读取它,但这是一个重量级的解决方案。现有工具可以做到这一点吗?
最佳答案
您可以使用 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;
}
}
关于Java 和 YAML : how to parse multiple yaml documents and merge them to a single YAML representation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345179/