是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。以上来自网络解释,spring-boot可支持这种格式的配置文件,下面介绍如何自己在java中解析这种文件
如下test.yml文件
定义javaBean(可直接映射成javaBean,当然也可以直接读入Map中)
方式一:snakeyaml
maven依赖添加
java代码:
-
@Test
-
public void testYml() {
-
org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml();
-
TestEntity testEntity = yaml.loadAs(DemoApplicationTests.class.getResourceAsStream("/test.yml"), TestEntity.class);//如果读入Map,这里可以是Mapj接口,默认实现为LinkedHashMap
-
System.out.println(testEntity);
-
}
方式二:jyaml
maven依赖添加
-
<dependency>
-
<groupId>org.jyaml</groupId>
-
<artifactId>jyaml</artifactId>
-
<version>1.3</version>
-
</dependency>
java代码:
-
@Test
-
public void testJyml() {
-
TestEntity testEntity = null;
-
try {
-
testEntity = org.ho.yaml.Yaml.loadType(DemoApplicationTests.class.getResourceAsStream("/test.yml"), TestEntity.class);//如果是读入Map,这里不可以写Ma接口,必须写实现
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
}
-
System.out.println(testEntity);
-
}
控制台输出:
TestEntity{age=418, name='Jack', params={event=what's up, url=http://www.test.com}, favoriteBooks=[Gone with the wind, The Little Prince]}