yaml文件读取转化为类
首先你要有一个文件读取的方法,写一个根据传入路径 + 类来自动返回对应类的方法。
/** * 根据传入的path,加载配置文件内容到对应class中 */ public static <T> T loadResources(String path,Class<T> clazz){ InputStream in = null; try { Yaml yaml = new Yaml(); // yaml文件路径 in = new FileInputStream(path); return yaml.loadAs(in, clazz); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } }
然后我们需要配置yaml文件及其对应实体类
注意事项!!!
①yaml文件中的内容必须对应实体类,只能少,不能多(yaml中有的字段,实体类必须有,实体类可以有自己的多的字段)
②实体类必须为public,否则yaml内容将无法加载
# yaml文件内容
versionUpdateSQL: - version: 1.0.0 updateSQL: - 1 - 2 - version: 1.0.1 updateSQL: - 1 - 2 - version: 1.0.2 updateSQL: - 1 - 2
// 实体类的内容 @Data public class VersionUpdateSQLList { private List<VersionUpdateSQL> versionUpdateSQL; @Data public static class VersionUpdateSQL { private String version; private List<String> updateSQL; } }