spring-boot - 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
了,但这根本没有被调用。
解决方案
尝试检查大小并初始化列表:
@ConstructorBinding
@ConfigurationProperties(prefix = "example")
public final class MyProps {
@NonNull
private final String neededProperty;
@Size(min=1)
private final List<String> lstNeededProperty = new ArrayList<>();
}
推荐阅读
- typescript - TSLint - 必须使用“finally”适当处理承诺
- python - Arcade 库需要 Python 3.6 或更高版本
- openapi - 如何在 OpenAPI 3.0 的模式中使用 $ref?
- visual-studio - 如何让 Visual Studio Community 2017 知道我的机器上已经安装了 .NET Core 2.1.500?
- angular - 从角度的子组件调用父组件的html id
- java - 使用特定时区设置时间选择器
- xml - 无法在 SOAP 中获取 XML 元素的路径
- python - 带有 Selenium 的 Python 下拉列表
- django - Django中一张表可以有多个主键吗?
- asp.net-mvc - 如何从 MVC 中的 View 获取模型中的数据?