Java 如何在Spring Boot中为yaml中的键值对定义空对象值?
这就是我的配置现在的样子:Java 如何在Spring Boot中为yaml中的键值对定义空对象值?,java,spring,spring-boot,yaml,key-value,Java,Spring,Spring Boot,Yaml,Key Value,这就是我的配置现在的样子: 这是一个键值=映射配置 密钥是作为ID的数字 价值是作为人的对象 对于第三个和第四个,我想将null设置为person对象 以下是java类: @Component @ConfigurationProperties(prefix = "setup") public class Setup { private Map<Integer, Person> identifications; getter/sett
- 这是一个键值=映射配置
- 密钥是作为ID的数字
- 价值是作为人的对象
- 对于第三个和第四个,我想将null设置为person对象
@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
}
}
如果我删除第三个和第四个(空的),应用程序将成功启动。
因此,在映射中插入一个值为null的键是一个问题。
有可能吗?我知道映射可以有空值。但我不知道如何在yml中将null对象指定为值。- 我假设,您不希望将
中的这两个键全部保留在一起以用于文档或其他目的,因为保留它们对创建的映射具有相同的效果yaml
- 看看这个问题。Springs
将null和empty转换为YamlProcessor
“”
- 如果您亲自定义这样的静态方法,它将起作用
YAML规范说
null
应该作为null值加载,但既然不是,请尝试!!空
。是的,我也红了该规范,并尝试了!!空,但没有帮助:(如果您提供!!空
,会发生什么?如果您无法让它工作,您可能需要走一条老路,创建一个从字符串
到人
的转换器,它将空
转换为空
。
@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
}
}
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [my.package.Setup.Person]
public static Person of(String value) {
if (value.trim().isEmpty())
return null;
throw new IllegalArgumentException();
}