使@ConfigurationProperties属性部分为强制性

Joh*_*pel 1 spring

给定以下简单(非嵌套)配置属性类:

@ConfigurationProperties("env")
public class MyServiceProperties {
  private String anyProperty;
  private Boolean anyOther;
...
Run Code Online (Sandbox Code Playgroud)

}

如何确保anyProperty是强制性的,即必须将env.any-property设置为启动应用程序?嵌套配置属性类有什么区别吗?

Sea*_*uit 5

您可以执行所有类型的验证。

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

您也可以在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;
   }
}
Run Code Online (Sandbox Code Playgroud)