I came across a problematic to which I can't find any nice solution. Some context: we work with several micro-services, most of which use rest clients. We found out that a lot of them will use similar configurations for similar issues (i.e. resiliency). Naturally, we want to extract common, heavily duplicated, non business code into a library. But here is the thing: How can I extract a @ConstructorBinding
@ConfigurationProperties
data class in a library (especially if there could be several instances of these classes in the code base that uses the library)?
Here is some example code:
@ConstructorBinding
@ConfigurationProperties(prefix = "rest.client")
data class MyDuplicatedRestClientProperties(
val host: String,
val someOtherField: Int,
val someFieldWithDefaultValue: String = "default value"
)
I would like to import this in a project to configure 2 different REST clients. I tried:
- Creating an abstract class my
ClientProperties
would extend. Sadly, I need to expose all the fields of the parent class which doesn't really help with duplication:
abstract class MyAbstractClient(
val host: String,
val someOtherField: Int,
val someFieldWithDefaultValue: String = "default value"
)
@ConstructorBinding
@ConfigurationProperties(prefix = "rest.client")
class MyImplematationClient(
val host: String,
val someOtherField: Int,
val someFieldWithDefaultValue: String = "default value"
): MyAbstractClient(
host,
someOtherField,
someFieldWithDefaultValue
)
- Instantiating the properties as a
@Bean
method with the@ConfigurationProperties
but this doesn't work well either as it forces me to put fields with@Value
in the@Configuration
class:
@Configuration
class MyConfigurationClass {
@Value("${my.client.host}")
lateinit var host: String
@Value("${my.client.someOtherField}")
lateinit var someOtherField: Int
@Value("${my.client.someFieldWithDefaultValue:default value}")
lateinit var someFieldWithDefaultValue: String
@Bean
@ConfigurationProperties
fun myClient() = MyDuplicatedRestClientProperties(
host,
someOtherField,
someFieldWithDefaultValue
)
}