1. package com.hq.schoolcj.util;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.yaml.snakeyaml.Yaml;
    4. import java.util.HashMap;
    5. import java.util.LinkedHashMap;
    6. import java.util.Map;
    7. import java.util.regex.Matcher;
    8. import java.util.regex.Pattern;
    9. /**
    10. * 获取yml参数配置帮助类
    11. */
    12. @Slf4j
    13. public class YamlUtil {
    14. private Pattern p1 = Pattern.compile("\\$\\{.*?\\}");
    15. /**
    16. * key:文件索引名
    17. * value:配置文件内容
    18. */
    19. private static Map<String , LinkedHashMap> ymls = new HashMap<>();
    20. /**
    21. * String:当前线程需要查询的文件名
    22. */
    23. private static ThreadLocal<String> nowFileName = new InheritableThreadLocal<>();
    24. /**
    25. * 加载配置文件
    26. * @param fileName
    27. */
    28. public static void loadYml(String fileName){
    29. nowFileName.set(fileName);
    30. if (!ymls.containsKey(fileName)){
    31. ymls.put(fileName , new Yaml().loadAs(YamlUtil.class.getResourceAsStream("/" + fileName),LinkedHashMap.class));
    32. }
    33. }
    34. /**
    35. * 读取yml文件中的某个value。
    36. * 支持解析 yml文件中的 ${} 占位符
    37. * @param key
    38. * @return Object
    39. */
    40. public Object getValue(String key){
    41. String[] keys = key.split("[.]");
    42. Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
    43. for (int i = 0; i < keys.length; i++) {
    44. Object value = ymlInfo.get(keys[i]);
    45. if (i < keys.length - 1){
    46. ymlInfo = (Map) value;
    47. }else if (value == null){
    48. throw new RuntimeException("key不存在");
    49. }else {
    50. String g;
    51. String keyChild;
    52. String v1 = (String)value;
    53. for(Matcher m = p1.matcher(v1); m.find(); value = v1.replace(g, (String)getValue(keyChild))) {
    54. g = m.group();
    55. keyChild = g.replaceAll("\\$\\{", "").replaceAll("\\}", "");
    56. }
    57. return value;
    58. }
    59. }
    60. return "";
    61. }
    62. /**
    63. * 读取yml文件中的某个value
    64. * @param fileName yml名称
    65. * @param key
    66. * @return Object
    67. */
    68. public Object getValue(String fileName , String key){
    69. loadYml(fileName);
    70. return getValue(key);
    71. }
    72. /**
    73. * 框架私有方法,非通用。
    74. * 获取 server.servlet.context-path的值
    75. * @return
    76. */
    77. public String getContextPath(){
    78. return (String) getValue("application.yml", "server.servlet.context-path");
    79. }
    80. /**
    81. * 读取yml文件中的某个value,返回String
    82. * @param fileName
    83. * @param key
    84. * @return String
    85. */
    86. public String getValueToString(String fileName , String key) {
    87. return (String) getValue(fileName, key);
    88. }
    89. }