默认情况下,我想拥有一个包含所有字段的不可变属性类。将属性包含到库中。
默认情况下,我可以使用简单类型创建不可变属性类,但不能使用复杂类型。有没有办法将复合类型的默认值设置为不可变的 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;
}
}
}
例如
sub
是 null
如果没有定义属性(使用 yaml
或 property file
)。我要
sub
与设置 finalValue
(与酒吧 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;
}
}
}
最佳答案
你非常接近。您可以简单地将 @DefaultValue 注释添加到该字段中,不带参数,添加到注释中:
public AnyProperties(
@DefaultValue("foo") String something,
@DefaultValue AnySubProperties sub
) {
this.something = something;
this.sub = sub; // Always null !
}
这样您就不需要 AnySubProperties 的默认构造函数。剩余的构造函数将用于创建具有默认值的 AnySubProperties 的实例。
关于java - ConfigurationProperties 和 ConstructorBinding 的复杂类型 DefaultValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60953959/