Spring 引导升级到 2.2.6 - 无法将 yaml 属性绑定到对象列表

Spring Boot Upgrade to 2.2.6 - Unable to bind yaml properties to list of objects

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

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

java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'webUiApplication.States': Could not bind properties to 'WebUiApplication.States' : prefix=states, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'states.defaults' to 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);
   }
}

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

重构您的代码:

州:

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

application.yaml

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

我们需要一个空对象,然后用数据填充它。这就是为什么我们不需要 args 构造函数。