YML的ConfigurationProperties加载列表 [英] ConfigurationProperties loading list from YML
问题描述
我正在尝试从YML加载配置.如果这些是逗号分隔的值,则可以加载值,也可以加载列表.但是我无法加载典型的YML列表.
I'm trying to load Configuration from YML. I can load value and I can also load list if these are comma seperated values. But i can't load a typical YML List.
配置类
@Component
@PropertySource("classpath:routing.yml")
@ConfigurationProperties
class RoutingProperties(){
var angular = listOf("nothing")
var value: String = ""
}
正在工作的路由.yml
angular: /init, /home
value: Hello World
不起作用routing.yml
angular:
- init
- home
value: Hello World
为什么我不能加载yml的第二个版本/我有语法错误?
Why can't i load the second version of yml / do I have a syntaxt error?
ENV:Kotlin,春季2.0.0.M3
ENV: Kotlin, Spring 2.0.0.M3
推荐答案
正如@flyx所说,@PropetySource
不适用于yaml文件.但是在春季,您可能会覆盖几乎所有内容:)
As @flyx say, @PropetySource
not worked with yaml files. But in spring you may override almost everything :)
PropertySource
具有附加参数:factory.可以基于DefaultPropertySourceFactory
PropertySource
has additional parameter: factory. It's possible to create your own PropertySourceFactory base on DefaultPropertySourceFactory
open class YamlPropertyLoaderFactory : DefaultPropertySourceFactory() {
override fun createPropertySource(name: String?, resource: EncodedResource?): org.springframework.core.env.PropertySource<*> {
if (resource == null)
return super.createPropertySource(name, resource)
return YamlPropertySourceLoader().load(resource.resource.filename, resource.resource, null)
}
}
并且在propertysource批注中使用此工厂时:
And when use this factory in propertysource annotation:
@PropertySource("classpath:/routing.yml", factory = YamlPropertyLoaderFactory::class)
最后,您需要使用mutableList初始化变量angular
Last that you need is to initialized variable angular with mutableList
完整代码示例:
@Component
@PropertySource("classpath:/routing.yml", factory = YamlPropertyLoaderFactory::class)
@ConfigurationProperties
open class RoutingProperties {
var angular = mutableListOf("nothing")
var value: String = ""
override fun toString(): String {
return "RoutingProperties(angular=$angular, value='$value')"
}
}
open class YamlPropertyLoaderFactory : DefaultPropertySourceFactory() {
override fun createPropertySource(name: String?, resource: EncodedResource?): org.springframework.core.env.PropertySource<*> {
if (resource == null)
return super.createPropertySource(name, resource)
return YamlPropertySourceLoader().load(resource.resource.filename, resource.resource, null)
}
}
@SpringBootApplication
@EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class))
open class Application {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val context = SpringApplication.run(Application::class.java, *args)
val bean = context.getBean(RoutingProperties::class.java)
println(bean)
}
}
}
这篇关于YML的ConfigurationProperties加载列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!