首页 > 解决方案 > ConfigurationProperties 和 ConstructorBinding 的复杂类型 DefaultValue

问题描述

默认情况下,我希望拥有一个包含所有字段的不可变属性类。将属性包含到库中。默认情况下,我可以使用简单类型创建不可变属性类,但不能使用复杂类型。有没有办法将复杂类型的默认值设置为不可变的 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;
       }
   }
}

例如subnull如果没有定义属性(使用yamlor property file)。
我想sub用 setted 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;
       }
   }
}

标签: javaspringspring-boot

解决方案


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

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

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


推荐阅读