java - 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;
}
}
}
例如sub
,null
如果没有定义属性(使用yaml
or 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;
}
}
}
解决方案
你非常亲近。您可以简单地将 @DefaultValue 注释添加到字段中,不带参数,到注释中:
public AnyProperties(
@DefaultValue("foo") String something,
@DefaultValue AnySubProperties sub
) {
this.something = something;
this.sub = sub; // Always null !
}
这样您就不需要 AnySubProperties 的默认构造函数。剩余的构造函数将用于创建具有默认值的 AnySubProperties 实例。
推荐阅读
- java - Can't use class because come components are package private
- oracle - 如何在 oracle 12.2 中建立有关程序执行的统计信息?
- spring-boot - 如何解决找不到能够从类型 TupleBackedMap 转换为类型 [com.example.dto.ExampleDto] 的转换器
- google-data-studio - 如何在 Data Studio 中为多个最终用户启用“按电子邮件过滤”?
- javascript - 如何将 Javascript html 文件中的元素值变量传递给 Google Apps 脚本中的 code.gs 文件?
- sql - 在没有关键字的情况下,使用多个连接计算大于和求和一个值的语法
- javascript - 带有 formvalidation 的正则表达式在每个字符后更改结果
- python - 自定义用户的不同登录视图
- microsoft-graph-api - 一个渠道(例如期刊或会议)被 Microsoft Academic Graph 索引的标准和/或流程是什么?
- javascript - 每次变量更改语句执行一个console.log