【问题标题】:Spring Boot Upgrade to 2.2.6 - Unable to bind yaml properties to list of objectsSpring Boot 升级到 2.2.6 - 无法将 yaml 属性绑定到对象列表
【发布时间】:2020-05-01 23:53:25
【问题描述】:

我正在将项目升级到 Spring Boot 2.2.6。以下编译错误将 yaml 属性数据绑定到对象列表 -

** 请注意项目是在之前版本的spring-boot(2.2.1)中编译的,我一直在使用**

java.lang.IllegalStateException: 无法加载 ApplicationContext 原因:org.springframework.boot.context.properties.ConfigurationPropertiesBindException:创建名为“webUiApplication.States”的bean时出错:无法将属性绑定到“WebUiApplication.States”:prefix=states,ignoreInvalidFields=false,ignoreUnknownFields=true;嵌套异常是 org.springframework.boot.context.properties.bind.BindException: 无法将 'states.defaults' 下的属性绑定到 java.util.List

application.yml

   states:
  defaults:
    -
      postal-code: AL
      name: Alabama
    -
      postal-code: AK
      name: Alaska
    -
      postal-code: AZ
      name: Arizona

配置

    @Data 
   @Configuration
   @ConfigurationProperties("states")
   public static class States {

      private List<State> defaults;

      private List<State> docVerify;

      private List<State> registration;

  }

POJO

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
public class State implements ListOption {
   public static final Comparator<State> DISPLAY_COMPARATOR = new ListOption.DisplayComparator<>();

   @NonNull private final String postalCode;

   @NonNull private final String name;

@Override
   @EqualsAndHashCode.Include
   public String getValue() {
      return this.postalCode;
   }

   @Override
   @ToString.Include
   public String getLabel() {
      return String.format("%s - %s", postalCode, name);
   }
}

遇到过成员收到类似问题但未能找到解决方案的帖子。期待您的意见。

【问题讨论】:

  • 你确定完全相同的代码在 spring boot 2.2.1 上工作吗?
  • 是的,它在以前的版本中运行良好,

标签: spring spring-boot yaml java-11


【解决方案1】:

重构你的代码:

州:

@Data

    @Configuration
    @ConfigurationProperties("states")
    @ToString
    @NoArgsConstructor
    public class States {
        private List<State> defaults;
        private List<State> docVerify;
        private List<State> registration;

    }

状态:

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
@NoArgsConstructor
public class State {
    @NonNull
    private String postalCode;

    @NonNull
    private String name;

    @EqualsAndHashCode.Include
    public String getValue() {
        return this.postalCode;
    }

    @ToString.Include
    public String getLabel() {
        return String.format("%s - %s", postalCode, name);
    }
}

应用程序.yaml

states:
  defaults:
    -
      postal-code: AL
      name: Alabama
    -
      postal-code: AK
      name: Alaska
    -
      postal-code: AZ
      name: Arizona

我们需要有一个空对象,然后用数据填充它。这就是我们不需要 args 构造函数的原因。

【讨论】:

  • 我想问题是为什么它在以前的版本中工作。这个新版本发生了什么变化导致它崩溃?可能会添加此信息会有所帮助
猜你喜欢
  • 2018-12-11
  • 2018-10-17
  • 1970-01-01
  • 2019-05-12
  • 2016-07-13
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
相关资源
最近更新 更多