读取内部的yml就不说了,直接用@value注解或者用snakeyaml就可以了,读取外部的我感觉目前最好用的就是用jackson-dataformat-yaml,自动解析,下面就贴出我的工具类
1、引入pom
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.12.3</version>
</dependency>
注:这里注意,pom的version不要更改,升级之后抛了一个异常,不想解决了;
2、自己写的util
/**
* desc: 获取yml值
* date: 2022-09-08
* @param ymlPath yml地址 例:E://file/application-timetask.yml
* @param cronName cron对应yml全路径名称 例:timetask.analysis.NeiWangTransitCarInfoTongBuTask.cron.executeTongNeiwangCarChange
**/
public static String getYmlValue(String ymlPath,String cronName){
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
InputStream input = null;
try {
input = new FileInputStream(ymlPath);
} catch (FileNotFoundException e) {
return null;
}
Map map;
try {
map = objectMapper.readValue(input, Map.class);
} catch (IOException e) {
return null;
}
String[] split = cronName.split("\\.");
Map info = new HashMap();
String cron = "";
for (int i = 0; i < split.length; i++) {
if (i ==0) {
info = (Map) map.get(split[i]);
}else if(i==split.length-1){
cron = (String) info.get(split[i]);
}else{
info = (Map) info.get(split[i]);
}
if (info==null) {
return null;
}
}
return cron;
}
下面是截图,我的yml文件
调用
输出: