如何在YAML资源文件中指定当前时间适配SnakeYaml的yaml.loadAs加载
问题根因
SnakeYaml 内置的!!timestamp标签仅支持解析符合RFC3339规范的固定格式时间字符串(例如2024-01-01T00:00:00+08:00),不识别now这类动态占位符。原有配置timestamp: !!timestamp now会直接触发解析报错,因为内置逻辑会尝试把字符串"now"解析为合法时间,校验不通过就抛出异常。
正确实现方式
方案1:自定义标签实现YAML内直接写当前时间占位
该方案在YAML解析阶段就自动完成时间替换,不需要加载后手动处理。
- 调整
example.yaml配置,去掉会触发解析报错的内置timestamp标签,改用自定义占位标签
additionalFields: eventtype: userchange listname: default timestamp: !now
- 修改Java加载逻辑,给SnakeYaml注册
!now标签的解析规则,遇到该标签时直接返回加载时刻的当前时间
try( InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("example.yaml")) { Constructor customConstructor = new Constructor(Example.class); // 注册!now标签的解析逻辑 customConstructor.yamlConstructors.put( new Tag("!now"), new Constructor() { @Override public Object construct(Node node) { return new java.util.Date(); } } ); Yaml yaml = new Yaml(customConstructor); topSettings = yaml.loadAs( in, Example.class ); }
解析完成后,additionalFields Map中的timestamp字段会自动填充为YAML加载时刻的当前时间,和现有Map<String, Object>的类型定义完全兼容,不需要修改原有类的字段结构。
方案2:加载后手动替换占位符
该方案不需要修改SnakeYaml的原生解析逻辑,适合不想调整YAML解析器配置的场景。
- 调整
example.yaml配置,去掉会触发解析报错的内置timestamp标签
additionalFields: eventtype: userchange listname: default timestamp: now
- 在Java加载逻辑末尾增加占位符判断替换
try( InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("example.yaml")) { Yaml yaml = new Yaml(); topSettings = yaml.loadAs( in, Example.class ); // 替换时间占位符 Object rawTimestamp = topSettings.getAdditionalFields().get("timestamp"); if ("now".equals(rawTimestamp)) { topSettings.getAdditionalFields().put("timestamp", new java.util.Date()); } }
注意事项
- 不要在
!!timestamp标签后接非RFC3339格式的字符串,内置标签的解析逻辑没有预留占位符扩展能力,格式不匹配会直接抛出解析异常。 - 由于
additionalFields是松散类型的Map,替换为Date、Instant、LocalDateTime等任意时间类型都可正常存储,不需要调整类定义。
内容的提问来源于stack exchange,提问作者user2706838
相关产品推荐
相关产品推荐

