【问题标题】:How to define null object value for key-value pair in yaml in Spring Boot?如何在 Spring Boot 的 yaml 中为键值对定义空对象值?
【发布时间】:2020-07-16 13:56:52
【问题描述】:

这就是我的配置现在的样子:

  • 这是一个键值 = 映射配置
  • key 是一个作为 ID 的数字
  • 值是作为人的对象
  • 第 3 次和第 4 次我想将 null 设置为 person 对象
setup:
    identifications:
        1:
            name: John
            age: 50
        2:
            name: Sarah
            agen: 40
        3: null
        4:
        5:
            name: Joe
            age: 20

这些是 java 类:

@Component
@ConfigurationProperties(prefix = "setup")
public class Setup {

    private Map<Integer, Person> identifications;
    
    getter/setter
    
    public static class Person {
    
        private String name;
        private Integer age;
        
        getters/setters
    
    }

}

启动spring boot应用后,出现以下异常:

Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [my.package.Setup.Person]

如果我删除第 3 个和第 4 个(空的),应用程序启动成功。 所以在映射中插入一个空值的键是有问题的。 有可能吗?我知道地图可以有空值。但我不知道如何将 null 对象指定为 yml 中的值。

【问题讨论】:

  • YAML 规范说 null 应该 加载为空值,但既然不是,请尝试使用 !!null
  • 是的,我也把那个规范加红了,并尝试使用 !!null 但没有帮助:(
  • 如果您提供!!null 会发生什么?如果你不能让它工作,你可能需要创建一个从StringPerson 的转换器,它将"null" 转换为null

标签: java spring spring-boot yaml key-value


【解决方案1】:
  • 我假设,您不想出于文档目的或其他目的将 yaml 中的这两个键一起保留,因为保留它们对创建的地图具有相同的效果

  • 看到这个问题。 Springs YamlProcessor 将 null 和 empty 转换为 ""https://github.com/spring-projects/spring-boot/issues/8873

  • 如果你亲自定义这样的静态方法,它会起作用

    public static Person of(String value) {
      if (value.trim().isEmpty())
        return null;
      throw new IllegalArgumentException();
    }

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 2016-03-06
    • 2019-07-11
    • 1970-01-01
    • 2018-12-11
    • 2021-12-08
    • 2021-03-06
    • 2020-02-06
    相关资源
    最近更新 更多