简体   繁体   中英

How to define null object value for key-value pair in yaml in Spring Boot?

This is how my configuration looks now:

  • this is a key-value = map configuration
  • key is a number as an ID
  • value is an object as a person
  • for the 3rd and 4th I wanted to setup null as person object
setup:
    identifications:
        1:
            name: John
            age: 50
        2:
            name: Sarah
            agen: 40
        3: null
        4:
        5:
            name: Joe
            age: 20

These are the java classes:

@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
    
    }

}

After starting spring boot application, I get the following exception:

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

If I delete the 3rd and 4th (the null ones), the application starts successfully. So it has a problem to insert a key into the map with null value. Is it possible somehow? I know that maps can have null values. But I don't know how to specify null object as a value in yml.

  • I assume, you don't want to leave those 2 keys all together from yaml for documentation purposes or something because leaving them have the same effect on the created map

  • See this issue. Springs YamlProcessor translates null and empty to "" . https://github.com/spring-projects/spring-boot/issues/8873

  • If you define a static method like this in person, it will work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM