gpt4 book ai didi

java - Spring配置-Arraylist的可选字段

转载 作者:行者123 更新时间:2023-12-02 10:49:07 28 4
gpt4 key购买 nike

我有一个包含嵌入式列表的 spring 配置类。该对象包含分隔平面文件的规范。

对于类型为decimalType 的实例,我希望在SchemaAttributes 类中具有用于精度和小数位数的可选字段。这些字段与任何其他数据类型都不相关。

如何为未提供精度/比例值的实例实现默认值?

@ConfigurationProperties(prefix = "source-parameters.file_schema")
@Configuration
public class FileSchema {

private List<SchemaAttributes> schema;

public FileSchema(List<SchemaAttributes> schema) {
this.schema = schema;
}

public FileSchema(){

}

public List<SchemaAttributes> getSchema() {
return schema;
}

public void setSchema(List<SchemaAttributes> schema) {
this.schema = schema;
}


public static class SchemaAttributes {

private String name;
private String type;
private Boolean nullable;
private int precision;
private int scale;

public SchemaAttributes(String name, String type, Boolean nullable) {
this.name = name;
this.type = type;
this.nullable = nullable;
this.precision = precision;
this.scale = scale;
}

public SchemaAttributes() {
}

// getters, setters

...
}

最佳答案

precisionscale 是原始 int ,因此如果构造函数未提供值 precision scale 将被初始化为 0。例如:

public SchemaAttributes(String name, String type, Boolean nullable) {
this.name = name;
this.type = type;
this.nullable = nullable;
//this.precision = precision; this.precision will be initialized to 0
//this.scale = scale; this.scale will be initialized to 0
}

但是委托(delegate)给另一个需要更多参数的构造函数是很常见的。例如:

public SchemaAttributes(String name, String type, Boolean nullable, int preciesion, int scale) {
this.name = name;
this.type = type;
this.nullable = nullable;
this.precision = precision;
this.scale = scale;
}

public SchemaAttributes(String name, String type, Boolean nullable) {
this(name, type, nullable, 0, 0);
}

public SchemaAttributes() {
this("unknown", "unknown", true);
}

有时参数的数量变得太大和/或构造函数的数量变得太大。如果创建实例变得困难/笨重,那么请考虑转向构建器模式。

关于java - Spring配置-Arraylist的可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com