You can create ConfigurationProperties
-Objects with Spring, in various ways.
One way, is to add the @ConfigurationProperties
-Annotation to an @Bean
-Declaration like so:
@Bean
@ConfigurationProperties("my.property.group")
public MyProperties myProperties() {
return new MyProperties();
}
which will create a bean from MyProperties
-class and consequently use its setters to fill its members with values from the configuration file.
You can also have the annotation directly on the MyProperties
-Object like so:
@ConfigurationProperties("my.property.group")
public class MyProperties {
@Getter @Setter private String myFirstValue;
@Getter @Setter private String mySecondValue;
}
creating it by placing @EnableConfigurationProperties(MyProperties.class)
to any loaded configuration.
It is also possible to create this class in an immutable way, using @ConstructorBinding
@ConfigurationProperties("my.property.group")
@ConstructorBinding
public class MyProperties {
@Getter private final String myFirstValue;
@Getter private final String mySecondValue;
public MyProperties(String myFirstValue, String mySecondValue) {
this.myFirstValue = myFirstValue;
this.mySecondValue = mySecondValue;
}
}
But how can I create immutable ConfigurationProperties in combination with the first @Bean-method?
I tried something like this:
@Bean
@ConfigurationProperties("my.property.group")
// @ConstructorBinding <---- This is not applicable to methods
public MyProperties myProperties(String myFirstValue, String mySecondValue) {
return new MyProperties(myFirstValue, mySecondValue);
}
which tells me, it could not autowire the parameters, I shall consider declaring some beans of type String