网上查了大部分资料,读取yaml文件有两种方式:

(1)利用spring的@Value(${})的方式,但是这种方式往往要配合Spring容器去做。

(2)另一种方式脱离Spring容器,采用流的方式读取yaml文件,并生成java对象

每种方式都有其应用的场景。我根据(2)的方式简单写了一个读取Yaml的配置类,通过key的方式获取值。

例如:application.yml

a:
    b:
        c:
            d: hahah
            e: heheh
            f: heiheihei
g: xixixi

       

key的格式:

假如获取d的值,key的格式为:a.b.c.d

假如获取g的值,key的格式为:g

工具类如下:

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class YamlReader {

	private static Map<String, Map<String, Object>> properties = new HashMap<>();

	/**
	 * 单例
	 */
	public static final YamlReader instance = new YamlReader();

	static {
		Yaml yaml = new Yaml();
		try (InputStream in = YamlReader.class.getClassLoader().getResourceAsStream("application.yml");) {
			properties = yaml.loadAs(in, HashMap.class);
		} catch (Exception e) {
			log.error("Init yaml failed !", e);
		}
	}

	/**
	 * get yaml property
	 * 
	 * @param key
	 * @return
	 */
	public Object getValueByKey(String key) {
		String separator = ".";
		String[] separatorKeys = null;
		if (key.contains(separator)) {
			separatorKeys = key.split("\\.");
		} else {
			return properties.get(key);
		}
		Map<String, Map<String, Object>> finalValue = new HashMap<>();
		for (int i = 0; i < separatorKeys.length - 1; i++) {
			if (i == 0) {
				finalValue = (Map) properties.get(separatorKeys[i]);
				continue;
			}
			if (finalValue == null) {
				break;
			}
			finalValue = (Map) finalValue.get(separatorKeys[i]);
		}
		return finalValue == null ? null : finalValue.get(separatorKeys[separatorKeys.length - 1]);
	}
}

测试代码(只是简单打印):

@Test
    public void testYamlReader() {
        Object serverHost = YamlReader.instance.getValueByKey("a.b.c.d");
        System.out.println(serverHost);
    }

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐