Chris Finlayson
Chris Finlayson

Reputation: 371

Spring configuration - Optional field of Arraylist

I have a spring configuration class containing an embedded List. The object contains specification of a delimited flat file.

I wish to have optional fields for precision and scale in the SchemaAttributes class for instances where type is decimalType. These fields are not relevant to any other datatype.

How do you implement a default value for instances where precision/scales values are not supplied?

@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

  ...
}

Upvotes: 0

Views: 327

Answers (1)

Andrew S
Andrew S

Reputation: 2801

precision and scale are primitive ints so if a constructor does not provide a value precision and scale will be initialized to 0. For example:

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
}

But it's common to delegate to another constructor which takes more arguments. For example:

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);
}

Sometimes the number of arguments grows too big and/or the number of constructors grows too big. If it becomes difficult/unwieldy to create an instance then consider moving to the Builder pattern.

Upvotes: 1

Related Questions