缘由:
因为加载顺序的问题,@Value、@Autowired这些都用不了,而我又需要读xxx.yml的配置文件,我就通过映射直接读取配置文件,得到一个Yaml对象(load),但是我发现,这个对象(load)不是我想要的效果,读取太麻烦,如下图,格式是一种嵌套的格式,想要获取其中一个参数很麻烦,而如果能转为key-value这种格式进行读取那么就方便很多。
解决方法:
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
public class YamlUtils {
private Map<String,Object> resultMap;
private String tempKey="";
public YamlUtils(){
resultMap=new LinkedHashMap<>();
}
private void SwitchYmalMapToMap(Object map){
if (!(map instanceof Map)) {
String substring = tempKey.substring(0, tempKey.length() - 1);
resultMap.put(substring,map);
return;
}
for (String key:((Map<String, Object>) map).keySet()){
tempKey += key+".";
SwitchYmalMapToMap(((Map<String, Object>) map).get(key));
tempKey=tempKey.substring(0,tempKey.length()-(key.length()+1));
}
}
public Map<String,Object> getYamlMap(String resources) throws IOException {
Yaml yaml = new Yaml();
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(resources);
if (StringUtils.isEmpty(resources)){
return null;
}
if (resourceAsStream==null){
return null;
}
Map load = yaml.load(resourceAsStream);
if (load==null||load.isEmpty()){
resourceAsStream.close();
return null;
}
SwitchYmalMapToMap(load);
resourceAsStream.close();
return this.resultMap;
}
}
然后直接调用传入配置文件名称就可以直接读取了,不会因容器加载顺序而导致读不到配置文件
实现之后的效果: