关于yaml是个什么东西,就不细说了。
yaml官方文档:http://www.yaml.org/
snakeyaml是用Java实现的解析yaml文件的库,官方wiki: https://bitbucket.org/asomov/snakeyaml/wiki/Documentation
下面上我解析yaml文件的例子:
// me.yaml
age: 1
name: jiaobuchong
params:
event: what's up
url: http://www.jiaobuchong.com
favoriteBooks:
- Gone with the wind
- The Little Prince
对应的JavaBean类:
// Me.java
public class Me {
private Integer age;
private String name;
private Map<String, Object> params;
private List<String> favoriteBooks;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public List<String> getFavoriteBooks() {
return favoriteBooks;
}
public void setFavoriteBooks(List<String> favoriteBooks) {
this.favoriteBooks = favoriteBooks;
}
@Override
public String toString() {
return "Me{" +
"age=" + age +
", name='" + name + '\'' +
", params=" + params +
", favoriteBooks=" + favoriteBooks +
'}';
}
}
将配置项隐射到JavaBean中:
public class TestMeYaml {
@Test
public void testParseMeYaml() throws FileNotFoundException {
Yaml yaml = new Yaml();
Me me = yaml.loadAs(new FileInputStream(new File("config/me.yaml")), Me.class);
System.out.println(me);
}
}
如果yaml文件中有一个参数没有配置,隐射到JavaBean中的值就是null。
网友评论