Java中yml、properties配置文件读取方式
1、properties配置文件读取
1 public class PropertyUtil { 2 private static String RESOURCE_NAME = "conf/sys.properties"; 3 private static Properties properties; 4 5 static { 6 try { 7 properties = PropertiesLoaderUtils.loadAllProperties(RESOURCE_NAME); 8 } catch (IOException e) { 9 } 10 } 11 12 public static String getValue(String key) { 13 return properties.getProperty(key); 14 } 15 }
2、yml配置文件读取
1 public class YamlUtil { 2 3 public static final YamlUtil instance = new YamlUtil(); 4 private static Map<String, Map<String, Object>> ymlMap = new HashMap<>(); 5 6 static { 7 Yaml yaml = new Yaml(); 8 try (InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream("application.yml");) { 9 ymlMap = yaml.loadAs(in, HashMap.class); 10 } catch (Exception e) { 11 } 12 } 13 20 public String getValue(String key) { 21 String separator = "."; 22 String[] separatorKeys = null; 23 if (key.contains(separator)) { 24 separatorKeys = key.split("\\."); 25 } else { 26 return ymlMap.get(key).toString(); 27 } 28 Map<String, Map<String, Object>> finalValue = new HashMap<>(); 29 for (int i = 0; i < separatorKeys.length - 1; i++) { 30 if (i == 0) { 31 finalValue = (Map) ymlMap.get(separatorKeys[i]); 32 continue; 33 } 34 if (finalValue == null) { 35 break; 36 } 37 finalValue = (Map) finalValue.get(separatorKeys[i]); 38 } 39 return finalValue == null ? null : finalValue.get(separatorKeys[separatorKeys.length - 1]).toString(); 40 } 41 }