Yaml 文件 “AppParams.yml” 与键值对:
someConfig:
key1: value1
key2: value2
POJO:
public class ApplicationParameters {
private Map<String, String> someConfig;
public ApplicationParameters() {
}
public Map<String, String> getSomeConfig() {
return someConfig;
}
public void setSomeConfig(Map<String, String> someConfig) {
this.someConfig = someConfig;
}
}
读者:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
File paramFile = new File("AppParams.yml");
ApplicationParameters applicationParameters = mapper.readValue(paramFile, ApplicationParameters.class);
Map<String, String> someConfig = applicationParameters.getSomeConfig();
String key1Value = someConfig.get("key1"); //returns "value1"
上面的示例在 POM.xml中使用了这些依赖项:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>