关键代码setSkipMissingProperties(true);
具体工具类代码如下:
import lombok.extern.slf4j.Slf4j; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.introspector.PropertyUtils; import java.io.FileInputStream; import java.io.InputStream; @Slf4j public class YamlUtil { // 变成驼峰样式 static String camelize(String input) { for (int i = 0; i < input.length(); i++) { if(input.substring(i, i+1).equals("-")) { input.replace("-", ""); input = input.substring(0, i) + input.substring(i+1, i+2).toUpperCase() + input.substring(i+2); } if(input.substring(i, i+1).equals(" ")) { input.replace(" ", ""); input = input.substring(0, i) + input.substring(i+1, i+2).toUpperCase() + input.substring(i+2); } } return input; } public static Yaml buildYamlInstance(Class<? extends Object> theRoot){ Constructor c = new Constructor(theRoot); c.setPropertyUtils(new PropertyUtils() { @Override public Property getProperty(Class<? extends Object> type, String name){ if ( name.indexOf('-') > -1 ) { name = YamlUtil.camelize(name); } // 关键代码 忽略yaml中无法在类中找到属性的字段 setSkipMissingProperties(true); return super.getProperty(type, name); } }); Yaml parser = new Yaml(c); return parser; } public static <T> T loadConfigFromFile(String path, Class<T> config_clazz) { Yaml yaml = YamlUtil.buildYamlInstance(config_clazz); T eConfig = null; try{ InputStream in = new FileInputStream(path); eConfig = yaml.loadAs(in, config_clazz); String configJson = JsonUtil.toJSONString(eConfig); eConfig = JsonUtil.parseObject(configJson, config_clazz); in.close(); }catch(Exception e){ log.error(String.format("load config file %s failed ...", path), e); } return eConfig; } }