[英]Spring JPA cannot map a field with custom setter in a Kotlin data class
[英]Kotlin Spring @Value for custom data class
我希望能够执行以下操作:
#application.yml
servers:
foo:
name: "Foo"
url: "http://localhost:8080/foo"
description: "Foo foo"
bar:
name: "Bar"
url: "http://localhost:8080/bar"
description: "Bar bar"
data class Server (
val name : String,
val url : String,
val description : String
)
然后在代码的某处
@Service
class LookupService (
@Value ("\${servers.foo}")
val fooServer : Server,
@Value ("\${servers.bar}")
val barServer : Server
) {
// do stuff
}
当我目前尝试时,我得到一个java.lang.IllegalArgumentException: Could not resolve placeholder 'servers.bar' in value "${servers.bar}"
在启动应用程序时。
有没有一种简单的方法可以做到这一点而无需在每个属性上专门执行@Value
?
我认为@Value
只能处理“叶”属性,即具有单个值的属性,而不是具有子属性的属性。
这是我对类型安全配置属性文档的理解。
在您的情况下,您可以做的是准备一个Servers
结构,该结构将包含 map 到某个点的整个配置树。 在您的情况下,您可以使用Server
类型的foo
和bar
属性创建它。
为了让它完全工作,您需要在代码中添加 3 个注释:
@EnableConfigurationProperties(Servers::class)
配置 class 以激活对服务器类型安全配置的支持@ConfigurationProperties("servers") on
服务器class, to tell Spring that Servers should be filled with data extracted from properties with
Servers
@ConstructorBinding
上的@ConstructorBinding,告诉 Spring 它是不可变的,必须使用构造函数注入值。您将在下面找到一个最小的工作示例:
@SpringBootApplication
@EnableConfigurationProperties(Servers::class)
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
data class Server(val name: String, val url: URL, val description: String)
@ConfigurationProperties("servers")
@ConstructorBinding
data class Servers(val foo: Server, val bar: Server)
@Service
class LookupService(servers : Servers) {
val foo = servers.foo
val bar = servers.bar
init {
println(foo)
println(bar)
}
}
启动时,示例应用程序会打印注入的配置:
Server(name=Foo, url=http://localhost:8080/foo, description=Foo foo)
Server(name=Bar, url=http://localhost:8080/bar, description=Bar bar)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.