原创

配置文件工具类,读取配置文件值

读取:properties 文件

public class PropertiesUtil {

    /**
     * 读取配置文件
     */
    private static Properties properties;
    static {
        try {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties"));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 根据属性key,获取String类型属性值
     * @param key
     * @return
     */
    public static String getValue(String key){
        String value = properties.getProperty(key);
        return value;
    }

}

读取 yaml 文件

public class YamlUtil {

    /**
     * 读取配置文件
     */
    private static Map<String, Map<String, Object>> ymlMap = new HashMap<>();

    static {
        Yaml yaml = new Yaml();
        try {
            InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream("application.yml");
            ymlMap = yaml.loadAs(in, HashMap.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据属性key,获取String类型属性值
     *
     * @param key
     * @return
     */
    public static String getValue(String key) {
        String separator = ".";
        String[] separatorKeys = null;
        if (key.contains(separator)) {
            separatorKeys = key.split("\\.");
        } else {
            return ymlMap.get(key).toString();
        }
        Map<String, Object> valueMap = new HashMap<>();
        for (int i = 0; i < separatorKeys.length - 1; i++) {
            if (i == 0) {
                valueMap = (Map) ymlMap.get(separatorKeys[i]);
                continue;
            }
            if (valueMap == null) {
                break;
            }
            valueMap = (Map) valueMap.get(separatorKeys[i]);
        }
        String value = (String)valueMap.get(separatorKeys[separatorKeys.length - 1]);
        return value;
    }

}
正文到此结束