本篇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