本篇blog主要是讨论:java
SnakeYAML是针对java语言的YAML解析器。若是想更多的了解SnakeYAML和YMAL,请看blog:vim
https://www.jianshu.com/p/dd4bb7305ccfmybatis
http://blog.csdn.net/conquer0715/article/details/42108061app
请看代码:ide
FileInputStream fileInputStream = null; try { Yaml yaml = new Yaml();//实例化解析器 File file = new File("inscriber-s\\src\\main\\resources\\application.yml");//配置文件地址 fileInputStream = new FileInputStream(file); Map map = yaml.loadAs(fileInputStream, Map.class);//装载的对象,这里使用Map, 固然也可以使用本身写的对象 //printMap(map, 0); }catch(FileNotFoundException e) { log.error("文件地址错误"); e.printStackTrace(); }finally { try { if(fileInputStream!=null) fileInputStream.close(); }catch (IOException e){ e.printStackTrace(); } }
如下面的.yml配置文件为例:函数
# mybatis mybatis: type-aliases-package: info.ideatower.component.inscriber.entity mapper-locations: classpath:mapping/*.xml config-locations: classpath:mybatis-config.xml # 应用组件通讯等配置 component: misso: log: addr: http://localhost:8009 error: enable: on Related: Projects: - Rx - Kwalify - yaml_vim - yatools.net - JSON - Pygments
使用SnakeYAML进行装载,实例化成Map对象(确切的说,应该是Map的子类,LinkedHashMap)。值得注意的是,要装载如此复杂的配置文件的,必须使用Map的嵌套,即:Map嵌套Map。具体请看下图:idea
其中,椭圆圈为key, 矩形圈的为value, 嵌套结构显而易先。以下图: spa
通常的,key的类类型老是java.lang.Stirng, 而value的类类型是不尽相同的。请看下图:.net
一段打印Map的数据的函数,若是读懂的话,会更加理解本篇blog的内容:code
private void printMap(Map map, int count){ Set set = map.keySet(); for(Object key: set){ Object value = map.get(key); for(int i=0; i<count; i++){ System.out.print(" "); } if(value instanceof Map) { System.out.println(key+":"); printMap((Map)value, count+1);//嵌套 }else if(value instanceof List){ System.out.println(key+":"); for(Object obj: (List)value){ for(int i=0; i<count; i++){ System.out.print(" "); } System.out.println(" - "+obj.toString()); } }else{ System.out.println(key + ": " + value); } } }
end