rob*_*011 5 spring yaml kotlin
我正在尝试从YML加载配置。如果这些是逗号分隔的值,则可以加载值,也可以加载列表。但是我无法加载典型的YML列表。
配置类别
@Component
@PropertySource("classpath:routing.yml")
@ConfigurationProperties
class RoutingProperties(){
var angular = listOf("nothing")
var value: String = ""
}
Run Code Online (Sandbox Code Playgroud)
工作routing.yml
angular: /init, /home
value: Hello World
Run Code Online (Sandbox Code Playgroud)
无法正常工作routing.yml
angular:
- init
- home
value: Hello World
Run Code Online (Sandbox Code Playgroud)
为什么我不能加载yml的第二个版本/我有语法错误?
ENV:Kotlin,春季2.0.0.M3
正如@flyx所说,@PropetySource
不适用于yaml文件。但是在春天,您可能会覆盖几乎所有内容:)
PropertySource
有附加参数:factory。可以基于DefaultPropertySourceFactory创建自己的PropertySourceFactory
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)
}
}
Run Code Online (Sandbox Code Playgroud)
并在propertysource批注中使用此工厂时:
@PropertySource("classpath:/routing.yml", factory = YamlPropertyLoaderFactory::class)
Run Code Online (Sandbox Code Playgroud)
最后,您需要使用mutableList初始化变量angular
完整代码示例:
@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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4071 次 |
最近记录: |