给出以下简单(非嵌套)配置属性类:
@ConfigurationProperties("env")
public class MyServiceProperties {
private String anyProperty;
private Boolean anyOther;
...
}
如何确保 anyProperty 是强制性的,即必须将env.any-property设置为启动应用程序? 嵌套配置属性类
有什么区别吗?答案 0 :(得分:4)
您可以执行所有类型的验证。
@Validated
@ConfigurationProperties("env")
public class MyServiceProperties {
@NotNull
@Min(5)
private String anyProperty;
// this is for nested objects
@Valid
@NotNull
private FooNested fooNested;
public static class FooNested{
@NotNull
private String someVal;
}
}
您还可以在setter中执行手动验证
@Validated
@ConfigurationProperties("env")
public class MyServiceProperties {
private String anyProperty;
public void setAnyProperty(String anyProp){
// just an example
if(anyProp.lenght < 6){
throw new RuntimeException();
}
this.anyProperty = anyProp;
}
}