我希望能夠執行以下操作:
#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對每個屬性進行操作?
uj5u.com熱心網友回復:
我認為這@Value只能處理“葉子”屬性,即具有單個值的屬性,而不是具有子項的屬性。
這是我對型別安全配置屬性檔案的理解。
在您的情況下,您可以做的是準備一個Servers結構,該結構將包含將您的整個配置樹映射到某個點。在您的情況下,您可以使用typefoo的bar屬性創建它Server。
要使其充分發揮作用,您需要在代碼中添加 3 個注釋:
@EnableConfigurationProperties(Servers::class)在配置類上激活對服務器型別安全配置的支持@ConfigurationProperties("servers") on服務器服務器class, to tell Spring that Servers should be filled with data extracted from properties with前綴@ConstructorBinding在Servers類上,告訴 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/511721.html
標籤:春天科特林春天的埃尔
