I realized a strange behavior in SpringBoot.
In a yml file I have the following configuration:
main:
record-id:
start-position: 1
value: 1
enabled: true
record-name:
start-position: 2
value: main
enabled: true
invented:
start-position: 3
value: 01012020
enabled: false
And these are the classes for it:
public class FieldType {
private Integer startPosition;
private String value;
private Boolean enabled;
getters/setters
}
@Component
@ConfigurationProperties(prefix = "main")
public class Main {
private FieldType recordId;
private FieldType recordName;
private FieldType invented;
getters/setters <-- sometimes without getters
}
As you can see, the main class has @ConfigurationProperties annotation to load the properties from yml into that bean.
And here is what I have found:
- if I don't provide getters for the fields in the main class, then sometimes the fields in the main call stay null, so not initiated
- if I restart the SpringBoot, then randomly other (1 or more) fields stay null, so not initiated
- if I restart the SpringBoot n times, then, again and again, random fields stay null
- if I provide getters for the fields in the main class, then all the fields will be always instantiated from tye yml file, no matter how many times I restart SpringBoot
Why is this? Why SpringBoot requires getters for fields which represent properties in yml?
You don't need getter's to bind the properties, you need setters to bind properties if you are using default constructor, docs
In case if you are initializing the
FieldType
inMain
class, then you don't need setters as wellYou can also use Constructor binding by completely avoiding setters
Just a note on Constructor Binding