java解析.yml文件
把yml文件中的datasource里所有字段的放入到一个map集合中
当想要获取数据库的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
/**
* 但是如果格式是这样的,或者有更深层次的,我们想动态获取datasource的map集合呢?
* 我们可以写一个方法,使用递归动态获取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)) //递归结束条件
return (Map) entry.getValue();
if (entry.getValue() instanceof Map) { //如果value是Map集合递归
maps = initYml((Map) entry.getValue(),str);
if (maps == null) //递归的结果如果为空,继续遍历
continue;
return maps; //不为空返回
}
}
return null;
}
}
二.优化代码,可在其他类中直接调用
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);
}
// 配置文件仅需要读取一次,读取配置文件的同时把数据保存到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)) // 递归结束条件
return (Map<String, Object>) obj;
if (entry.getValue() instanceof Map) {//如果value是Map集合递归
maps = getMapByName((Map<String, Object>) obj, name);
if (maps == null) //递归的结果如果为空,继续遍历
continue;
return maps; //不为空返回
}
}
return null;
}
}
}
膜拜大佬,写的不好勿喷~