In a kotlin/spring boot project, I can create a bean from a property file with this syntax
@Component
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
var name: String = ""
)
I don't find a way to make the object immutable, all properties must be var
. Is there a better way?
CodePudding user response:
As of Spring Boot 2.2, we can use the @ConstructorBinding
annotation to bind our configuration properties.
This essentially means that @ConfigurationProperties-annotated classes may now be immutable.
The @ConstructorBinding
annotation indicates that configuration properties should be bound via constructor arguments rather than by calling setters
It's important to emphasize that to use the constructor binding, we need to explicitly enable our configuration class either with @EnableConfigurationProperties
or with @ConfigurationPropertiesScan
If you don't have config class you can add it above the main application class:
@SpringBootApplication
@EnableConfigurationProperties(MyAwesome::class)
CodePudding user response:
have you tried this?
@ConstructorBinding
@ConfigurationProperties(prefix = "my.awesome.prop")
data class MyAwesome(
val name: String
)
then for instance in your configuration class:
@Configuration
@EnableConfigurationProperties(MyAwesome::class)
class MyConfig(private val myAwesome: MyAwesome) {}