首页 > 解决方案 > SpringBoot 检查注入的属性是否设置为 NotNull

问题描述

我知道我可以使用以下构造轻松地在 SpringBoot 2.2 中注入属性文件

@ConstructorBinding
@ConfigurationProperties(prefix = "example")
@Data
@AllArgsConstructor
public final class MyProps {

  @NonNull
  private final String neededProperty;
  @NonNull
  private final List<SampleProps> lstNeededProperty;

  public String getFirstSample(){
    return lstNeededProperty.get(0); //throws NPE
  }

}

@ConstructorBinding
@AllArgsConstructor
@Data
public class SampleProps {
  String key;
  String label;
}

和 yml 文件,如:

expample:
  neededProperty: test1
  lstNeededProperty:
    -key: abc
     label: input

对于-@NonNull来说效果很好,String但对于 - 失败了,List因为即使设置了列表也会抛出 NPE。

有没有一种简单的方法来检查是否List已初始化?我试过@Postconstruct了,但这根本没有被调用。

标签: spring-boot

解决方案


尝试检查大小并初始化列表:

@ConstructorBinding
@ConfigurationProperties(prefix = "example")
public final class MyProps {

  @NonNull
  private final String neededProperty;
  @Size(min=1)
  private final List<String> lstNeededProperty = new ArrayList<>();
}

推荐阅读