Let's say I have one file, defaults.yaml
:
pool:
idleConnectionTestPeriodSeconds: 30
idleMaxAgeInMinutes: 60
partitionCount: 4
acquireIncrement: 5
username: dev
password: dev_password
and another file, production.yaml
:
pool:
username: prod
password: prod_password
At runtime, how do I read both files and merge them into one such that the application 'sees' the following?
pool:
idleConnectionTestPeriodSeconds: 30
idleMaxAgeInMinutes: 60
partitionCount: 4
acquireIncrement: 5
username: prod
password: prod_password
Is this possible with, say, SnakeYAML? Any other tools?
I know one option is to read multiple files in as Maps and then merge them myself, render the merge to a single temporary file and then read that, but that's a heavyweight solution. Can an existing tool do this already?
You can use Jackson, the key is using ObjectMapper.readerForUpdating() and annotate the field with @JsonMerge (or all the missing fields in next objects will overwrite the old one):
Maven:
<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>
Code:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With