如何在spring boot中优雅的获取.yml文件工具类呢
代码如下:
package com.common. .utils. ;
import com.common. .generator.ResourceManager;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* yml文件工具类
*/
public class YmlUtils {
private static String bootstrap_file = \"bootstrap.yml\";
private static Map<String,String> result = new HashMap<>();
/**
* 根据文件名获取yml的文件内容
* @return
*/
public static Map<String,String> getYmlByFileName(String file){
result = new HashMap<>();
if(file == null)
file = bootstrap_file;
InputStream in = ResourceManager.class.getClassLoader().getResourceAsStream(file);
Yaml props = new Yaml();
obj = props.loadAs(in,Map.class);
Map<String, > param = (Map<String, >) obj;
for(Map.Entry<String, > entry:param.entrySet()){
String key = entry.getKey();
val = entry.getValue();
if(val instanceof Map){
forEachYaml(key,(Map<String, >) val);
}else{
result.put(key,val.toString());
}
}
return result;
}
/**
* 根据key获取值
* @param key
* @return
*/
public static String getValue(String key){
Map<String,String> map = getYmlByFileName(null);
if(map==null)return null;
return map.get(key);
}
/**
* 遍历yml文件,获取map集合
* @param key_str
* @param obj
* @return
*/
public static Map<String,String> forEachYaml(String key_str,Map<String, > obj){
for(Map.Entry<String, > entry:obj.entrySet()){
String key = entry.getKey();
val = entry.getValue();
String str_new = \"\";
if(StringUtils.isNotNull(key_str)){
str_new = key_str+ \".\"+key;
}else{
str_new = key;
}
if(val instanceof Map){
forEachYaml(str_new,(Map<String, >) val);
}else{
result.put(str_new,val.toString());
}
}
return result;
}
/**
* 获取bootstrap.yml的name
* @return
*/
public static String getApplicationName(){
return getYmlByFileName(bootstrap_file).get(\"spring.application.name\");
}
/**
* 获取bootstrap.yml的name
* @return
*/
public static String getApplicationName1(){
String name = getYmlByFileName(bootstrap_file).get(\"spring.application.name\");
return name + \"center\";
}
public static void main(String[] args) {
System.out.println(getApplicationName());
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
继续阅读与本文标签相同的文章
上一篇 :
JMeter,判断字符串是否存在该集合
下一篇 :
Python实现的批量修改文件后缀名操作示例
-
阿里云创新中心蔡素卿:双创是阿里发展生态业务的有力抓手
2026-05-19栏目: 教程
-
通过命令行参数发送阿里云短信 - python
2026-05-19栏目: 教程
-
阿里IOT智能人居邢超:开放阿里生态,助力消费级物联网产业全链路升级
2026-05-19栏目: 教程
-
Cassandra监控运维介绍
2026-05-19栏目: 教程
-
C#读写Excel
2026-05-19栏目: 教程
