为什么使用SnakeYaml结合Lombok时无法正常解析YAML字符串?
问题根因
报错的核心原因是@Accessors(chain = true)注解与SnakeYaml默认的JavaBean属性识别规则冲突:
- Lombok的
@Accessors(chain = true)会生成返回值为当前类对象的setter方法(格式为public YamlConfig setText(String text)),不符合标准JavaBean规范要求的setter返回值为void的规则 - SnakeYaml默认只识别返回值为
void的setXxx格式方法作为可写属性,因此找不到text字段对应的写入方法,抛出No writable property异常
解决方案
可以根据自身需求选择以下任意一种方案:
方案1:移除链式访问配置
如果不需要链式调用特性,直接删除@Accessors(chain = true)注解即可,Lombok会自动生成符合JavaBean规范的void返回值setter,SnakeYaml可直接识别。
修改后的Bean代码:
package main; import lombok.Data; @Data public class YamlConfig { private String text; }
方案2:保留链式访问,调整SnakeYaml配置
如果需要保留链式调用特性,可自定义SnakeYaml的属性识别规则,允许识别带返回值的setter:
修改后的测试代码:
public static void loadYaml(){ Constructor constructor = new Constructor(YamlConfig.class); PropertyUtils propertyUtils = new PropertyUtils(); // 配置允许setter方法有返回值 propertyUtils.setAllowReadOnlyProperties(true); constructor.setPropertyUtils(propertyUtils); Yaml yaml = new Yaml(constructor); YamlConfig config = yaml.load("text: testText"); log.info("text is {}",config.getText()); }
调整后无需修改原有Bean定义,即可同时支持链式调用和SnakeYaml解析。
内容的提问来源于stack exchange,提问作者Marek Andreansky
相关产品推荐
相关产品推荐

