ConfigurationProperties 和 ConstructorBinding 的复杂类型 DefaultValue

Gab*_*ROQ 7 java spring spring-boot

我想要一个默认情况下包含所有字段的不可变属性类。将财产纳入图书馆。默认情况下,我可以创建一个具有简单类型的不可变属性类,但不能使用复杂类型。有没有办法将复杂类型的默认值设置为不可变的 ConfigurationProperties 类?

import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.context.properties.bind.DefaultValue;

@ConfigurationProperties(prefix = "foo")
@ConstructorBinding
@Getter
public final class AnyProperties {
   private final String something
   private final AnySubProperties sub;

   public AnyProperties(
      @DefaultValue("foo") String something, 
      AnySubProperties sub // Any annotation here ? Like @DefaultValue
   ) {
       this.something = something;
       this.sub = sub; // Always null !
   }

   @Getter
   public static final class AnySubProperties {
       private String finalValue;

       public AnySubProperties(@DefaultValue("bar") String finalValue) {
          this.finalValue = finalValue;
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

例如subnull如果没有定义属性(使用yamlproperty file)。
我想要sub设置finalValue(带有 bar value)。

感谢您的回答。

使用不带注释的解决方案进行编辑

我找到了一个没有注释的解决方案,但我是一个懒惰的孩子,那为什么不可能有一个带有 spring 注释的解决方案呢?

import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.context.properties.bind.DefaultValue;

@ConfigurationProperties(prefix = "foo")
@ConstructorBinding
@Getter
public final class AnyProperties {
   private final String something
   private final AnySubProperties sub;

   @ConstructorBinding
   public AnyProperties(
      @DefaultValue("foo") String something, 
      AnySubProperties sub // Any annotation here ? Like @DefaultValue
   ) {
       this.something = something;
       this.sub = null != sub ? sub : new AnySubProperties();
   }

   @Getter
   public static final class AnySubProperties {
       private static final String DEFAULT_FINAL_VALUE = "bar";
       private String finalValue;

       public AnySubProperties() {
           this(DEFAULT_FINAL_VALUE);
       }

       @ConstructorBinding
       public AnySubProperties(@DefaultValue(DEFAULT_FINAL_VALUE) String finalValue) {
          this.finalValue = finalValue;
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你们非常亲密。您可以简单地将@DefaultValue注释添加到字段中,不带参数,添加到注释中:

public AnyProperties(
      @DefaultValue("foo") String something, 
      @DefaultValue AnySubProperties sub
   ) {
       this.something = something;
       this.sub = sub; // Always null !
   }
Run Code Online (Sandbox Code Playgroud)

这样您就不需要 AnySubProperties 的默认构造函数。剩余的构造函数将用于创建具有默认值的 AnySubProperties 实例。