java解析.yml文件方式
java解析.yml文件
把yml文件中的datasource里所有字段的放入到一個map集合中
當(dāng)想要獲取數(shù)據(jù)庫的url時,可以直接使用map.get(“url”)獲取得到.
*.yml文件
server: port: 8090 context-path: /myService spring: application: name: AAService datasource: url: jdbc:mysql://localhost:3306/bc username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver jpa: show-sql: false properties: hibernate: jdbc: batch_size: 100 order_inserts: true order_updates: true cloud: service-registry: auto-registration: enabled: false
*.引入pom包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.9.5</version> </dependency>
一.測試代碼
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.yaml.snakeyaml.Yaml; public class Test { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Yaml yml = new Yaml(); //配置文件路徑 String path = Object.class.getResource("/").getPath().substring(1)+ "application.yml"; InputStream reader = new FileInputStream(new File(path)); //yml讀取配置文件,指定返回類型為Map,Map中value類型為LinkedHashMap Map map = yml.loadAs(reader, Map.class); /** * eg:獲取server中的port * server: port: 8090 context-path: /myService */ Map mapServer = (Map)map.get("server"); String port = mapServer.get("port").toString(); System.out.println(port);//輸出8090 /** * 但是如果格式是這樣的,或者有更深層次的,我們想動態(tài)獲取datasource的map集合呢? * 我們可以寫一個方法,使用遞歸動態(tài)獲取map spring: datasource: url: jdbc:mysql://localhost:3306/bc username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver */ //傳入想要得到的字段 Map datasourceMap = initYml(map,"datasource"); System.out.println(datasourceMap.get("url"));//jdbc:mysql://localhost:3306/bc System.out.println(datasourceMap.get("username"));//root System.out.println(datasourceMap.get("password"));//123456 System.out.println(datasourceMap.get("driver-class-name"));//com.mysql.jdbc.Driver } public static Map initYml(Map map,String str) { Map maps = new HashMap(); Set<Map.Entry<String, Object>> set = map.entrySet(); for (Map.Entry<String, Object> entry : set) {//遍歷map if (entry.getKey().equals(str)) //遞歸結(jié)束條件 return (Map) entry.getValue(); if (entry.getValue() instanceof Map) { //如果value是Map集合遞歸 maps = initYml((Map) entry.getValue(),str); if (maps == null) //遞歸的結(jié)果如果為空,繼續(xù)遍歷 continue; return maps; //不為空返回 } } return null; } }
二.優(yōu)化代碼
可在其他類中直接調(diào)用
import java.io.File; import java.io.FileReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.yaml.snakeyaml.Yaml; public class YmlUtil { /** * 獲取yml文件中的指定字段,返回一個map * * @param sourcename * @return */ public static Map<String, Object> getResMap(String sourcename) { return YmlInit.getMapByName(YmlInit.ymlMap, sourcename); } // 配置文件僅需要讀取一次,讀取配置文件的同時把數(shù)據(jù)保存到map中,map定義為final,僅可以被賦值一次 private static class YmlInit { //初始化文件得到的map private static final Map<String, Object> ymlMap = getYml(); // 讀取配置文件,并初始化ymlMap private static Map<String, Object> getYml() { Yaml yml = new Yaml(); String path = Object.class.getResource("/").getPath().substring(1) + "application.yml"; Reader reader = null; try { reader = new FileReader(new File(path)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return yml.loadAs(reader, Map.class); } // //傳入想要得到的字段 private static Map<String, Object> getMapByName(Map<String, Object> map, String name) { Map<String, Object> maps = new HashMap<String, Object>(); Set<Map.Entry<String, Object>> set = map.entrySet(); for (Map.Entry<String, Object> entry : set) {// 遍歷map Object obj = entry.getValue(); if (entry.getKey().equals(name)) // 遞歸結(jié)束條件 return (Map<String, Object>) obj; if (entry.getValue() instanceof Map) {//如果value是Map集合遞歸 maps = getMapByName((Map<String, Object>) obj, name); if (maps == null) //遞歸的結(jié)果如果為空,繼續(xù)遍歷 continue; return maps; //不為空返回 } } return null; } } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java?Thread.currentThread().getName()?和?this.getName()區(qū)別詳
本文主要介紹了Thread.currentThread().getName()?和?this.getName()區(qū)別詳解,TestThread?testThread?=?new?TestThread();2022-02-02Spring Cloud Gateway組件的三種使用方式實例詳解
Spring Cloud Gateway是 Spring 官方基于 Spring5.0 、 SpringBoot2.0 和 Project Reactor 等技術(shù)開發(fā)的網(wǎng)關(guān)旨在為微服務(wù)框架提供一種簡單而有效的統(tǒng)一的API 路由管理方式,統(tǒng)一訪問接口,這篇文章主要介紹了Spring Cloud Gateway組件的三種使用方式,需要的朋友可以參考下2024-01-01解決子線程中獲取不到HttpServletRequest對象的問題
這篇文章主要介紹了解決子線程中獲取不到HttpServletRequest對象的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07spring framework體系結(jié)構(gòu)及模塊jar依賴關(guān)系詳解
在本篇文章里小編給大家整理的是關(guān)于spring framework體系結(jié)構(gòu)及模塊jar依賴關(guān)系,對此有興趣的朋友們可以學(xué)習(xí)下。2019-09-09