![](/img/trans.png)
[英]Why is Spring @ConstructorBinding not binding for Kotlin @ConfigurationProperties class?
[英]Spring Kotlin @ConfigurationProperties for data class defined in dependency
我有一个库,它的配置 class(没有 spring 配置类)定义为数据 class。 我想要一个可以通过 application.properties 配置的配置的 Bean。 问题是我不知道如何告诉 Spring 根据外部数据 class 创建 ConfigurationProperties。 我不是配置 class 的作者,所以我不能注释 class 本身。 @ConfigurationProperties 与 @Bean 一起不起作用,因为属性是不可变的。 这甚至可能吗?
如果我理解正确,您是否需要一种方法将第三方 object 转换为具有application.properties
文件中属性的 bean?
给定一个application.properties
文件:
third-party-config.params.simpleParam=foo
third-party-config.params.nested.nestedOne=bar1
third-party-config.params.nested.nestedTwo=bar2
创建一个 class 以从属性文件接收您的参数
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
@Configuration
@ConfigurationProperties(prefix = "third-party-config")
data class ThirdPartConfig(val params: Map<String, Any>)
这是您要使用的 object 的示例
class ThirdPartyObject(private val simpleParam: String, private val nested: Map<String, String>) {
fun printParams() =
"This is the simple param: $simpleParam and the others nested ${nested["nestedOne"]} and ${nested["nestedTwo"]}"
}
使用将您的第三方 object 转换为可注入 bean 的方法创建配置 class。
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class ThirdPartObjectConfig(private val thirdPartConfig: ThirdPartConfig) {
@Bean
fun thirdPartyObject(): ThirdPartyObject {
return ThirdPartObject(
simpleParam = thirdPartConfig.params["simpleParam"].toString(),
nested = getMapFromAny(
thirdPartConfig.params["nested"]
?: throw IllegalStateException("'nested' parameter must be declared in the app propertie file")
)
)
}
private fun getMapFromAny(unknownType: Any): Map<String, String> {
val asMap = unknownType as Map<*, *>
return mapOf(
"nestedOne" to asMap["nestedOne"].toString(),
"nestedTwo" to asMap["nestedTwo"].toString()
)
}
}
因此,现在您可以将您的第三方 object 作为 bean 注入,并从您的application.properties
文件中自定义配置参数
@SpringBootApplication
class StackoverflowAnswerApplication(private val thirdPartObject: ThirdPartObject): CommandLineRunner {
override fun run(vararg args: String?) {
println("Running --> ${thirdPartObject.printParams()}")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.