I have a config class FooConfig, in which i have a bound class 'Foo'.
@Configuration
@ConfigurationProperties("foo")
public class FooConfig {
  @Value("${foo.default.iterations}")
  private Integer iterations;
  private Foo foo;
  // getter / setter
}
In my class Foo I want the iterations-variable set with an existing default configuration-value, when not explicitly set in the properties-file.
public class Foo {
  private String name;
  @Value("${foo.default.iterations}")
  private Integer iterations;
  // getter / setter
}
My properties file
foo.default.iterations=999
# if this is set this config is bound (wins) in FooConfig-class as expected
# foo.iterations=111
foo.foo.name=foo
Setting a default value in FooConfig works, but not in my bound class Foo. 
What am I missing here?
Spring Boot @ConfigurationProperties is annotation for externalized configuration. To inject property value from a property file to a class, we can add @ConfigurationProperties at a class level with stereotype annotations such as @Component or add @ConfigurationProperties to a @Bean method in a @Configuration class.
@ConfigurationProperties allows to map the entire Properties and Yaml files into an object easily. It also allows to validate properties with JSR-303 bean validation. By default, the annotation reads from the application.
To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.
The @Value annotation is a pre-defined annotation used to read values from any property files under the project's classpath.
You shouldn't mix @Value and @ConfigurationProperties in the same class. If you want to have default values in a @ConfigurationProperties-annotated class, you can configure the fields with a default value:
@ConfigurationProperties("foo")
public class FooConfig {
    private Integer iterations = 999;
    // getter / setter
}
This change brings with it the added benefit of including the default value in the metadata that's generated by spring-boot-configuration-processor. The metadata is used by your IDE to provide auto-completion when you're editing application.properties and application.yaml files.
Lastly, and not directly related to your problem, a @ConfigurationProperties-annotated class should not be annotated with @Configuration. An @Configuration-annotated class is used to configure beans via @Bean methods. Your FooConfig class should either be annotated with @Component or you should use @EnableConfigurationProperties(FooConfig.class) on the @Configuration class that wants to use FooConfig.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With