java解析.yml文件方式
更新時間:2024年01月15日 09:27:49 作者:奈何、草
這篇文章主要介紹了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)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作
這篇文章主要介紹了SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作,需要的朋友可以參考下2018-03-03
swagger整合gateway實(shí)現(xiàn)文檔集中化過程
本文介紹了如何將Swagger與Spring?Cloud?Gateway整合,實(shí)現(xiàn)API文檔的集中化管理,通過Spring?Boot的自動裝配,配置了網(wǎng)關(guān)Swagger資源提供程序,實(shí)現(xiàn)了通過gateway路由的方式聚合Swagger文檔,整個過程包括了文件夾結(jié)構(gòu)、自動裝配文件內(nèi)容等詳細(xì)步驟2026-02-02
@RequestController之?dāng)?shù)據(jù)源與連接池使用及說明
文章總結(jié):介紹了Spring MVC中的@Controller和@ResponseBody注解以及@RequestMapping注解的使用方法,詳細(xì)講解了數(shù)據(jù)源、連接池的概念及其在Java項(xiàng)目中的應(yīng)用,包括JNDI、DBCP、C3P0和Druid等連接池的配置和特點(diǎn)2026-01-01
Java線程的生命周期命名與獲取代碼實(shí)現(xiàn)
這篇文章主要介紹了Java線程的生命周期命名與獲取代碼實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

