美文网首页
SpringBoot 注入配置报错“The elements w

SpringBoot 注入配置报错“The elements w

作者: 极简架构 | 来源:发表于2024-02-05 16:12 被阅读0次

    SpringBoot 注入配置报错“The elements were left unbound

    SpringBoot2.4 注入自定义注解配置,nacos配置中心拉取配置报错 The elements [sh.dn.persons[0].age,sh.dn.persons[0].name,sh.dn.persons[1].age,sh.dn.persons[1].name] were left unbound.


    image.png

    自定义配置


    image.png
    
    import lombok.Data;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    
    @ConfigurationProperties(prefix = "sh.dn")
    @Component
    @Data
    @ConditionalOnProperty(value = "sh.dn.enable", havingValue = "true", matchIfMissing = false)
    public class RIdConfig {
    
        private Boolean enable;
        private String test;
        private List<Person> persons;
    
    }
    
    
    public class Person {
      private String name;
      private Integer age;
    }
    

    Person类


    image.png

    nacos配置中心配置,没有问题

    sh:
      dn:
        enable: true
        test: test_jz
        persons:
        - age: 19
          name: 张三
        - age: 20
          name: 李四
    

    问题原因

    Person类中使用了lombok来生成get、set方法,缺少无参数的构造器,所以SpringBoot 启动无法创建对象,导致无法正常注入配置值

    fix方案

    添加lombok注解,生成无参构造器即可


    image.png
    @NoArgsConstructor
    @Data
    public class Person {
      private String name;
      private Integer age;
    }
    

    参考
    https://stackoverflow.com/questions/56637271/reason-the-elements-were-left-unbound
    https://blog.csdn.net/cnds123321/article/details/118117356

    相关文章

      网友评论

          本文标题:SpringBoot 注入配置报错“The elements w

          本文链接:https://www.haomeiwen.com/subject/hwmqadtx.html