【发布时间】:2020-08-26 18:09:21
【问题描述】:
我遇到了一个问题,我找不到任何好的解决方案。一些背景:我们使用几个微服务,其中大多数使用休息客户端。我们发现他们中的很多人会使用类似的配置来解决类似的问题(即弹性)。自然,我们希望将常见的、大量重复的、非业务代码提取到库中。但问题是:如何在库中提取 @ConstructorBinding @ConfigurationProperties 数据类(尤其是在使用该库的代码库中可能存在这些类的多个实例时)?
下面是一些示例代码:
@ConstructorBinding
@ConfigurationProperties(prefix = "rest.client")
data class MyDuplicatedRestClientProperties(
val host: String,
val someOtherField: Int,
val someFieldWithDefaultValue: String = "default value"
)
我想在一个项目中导入它来配置 2 个不同的 REST 客户端。我试过了:
- 创建一个抽象类我的
ClientProperties将扩展。可悲的是,我需要公开父类的所有字段,这对复制没有帮助:
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
)
- 使用
@ConfigurationProperties将属性实例化为@Bean方法,但这也不能很好地工作,因为它迫使我将带有@Value的字段放在@Configuration类中:
@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
)
}
【问题讨论】:
-
也许你会发现这个有用:stackoverflow.com/a/49423156/1970670
标签: spring-boot kotlin