如何在spring boot
中优雅的获取.yml
文件工具类呢
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
package com.common.base.utils.base;
import com.common.base.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();
object obj = props.loadas(in,map. class );
map<string,object> param = (map<string, object>) obj;
for (map.entry<string,object> entry:param.entryset()){
string key = entry.getkey();
object val = entry.getvalue();
if (val instanceof map){
foreachyaml(key,(map<string, object>) 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, object> obj){
for (map.entry<string,object> entry:obj.entryset()){
string key = entry.getkey();
object 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, object>) 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());
}
}
|
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接