spring - 如何在 Kotlin 中使用 @ConfigurationProperties
问题描述
我有这个自定义对象:
data class Pair(
var first: String = "1",
var second: String = "2"
)
现在我想用我的自动装配它application.yml
:
my-properties:
my-integer-list:
- 1
- 2
- 3
my-map:
- "abc": "123"
- "test": "test"
pair:
first: "abc"
second: "123"
使用这个类:
@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
lateinit var myIntegerList: List<Int>
lateinit var myMap: Map<String, String>
lateinit var pair: Pair
}
在添加之前Pair
它工作正常,但在我得到之后Reason: lateinit property pair has not been initialized
这是我的main
:
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@RestController
class MyRestController(
val props: ComplexProperties
) {
@GetMapping
fun getProperties(): String {
println("myIntegerList: ${props.myIntegerList}")
println("myMap: ${props.myMap}")
println("pair: ${props.pair}")
return "hello world"
}
}
使用 java 我已经完成了这个,但是我看不到这里缺少什么。
解决方案
你不能用 lateinit var 做到这一点。
解决方案是将您的 pair 属性初始化为 null:
@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
...
var pair: Pair? = null
}
或者用默认值实例化你的对:
@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
...
var pair = Pair()
}
你现在可以用你的 application.yml 自动装配它:
...
pair:
first: "abc"
second: "123"
推荐阅读
- powershell - 在模块 Posh-ssh 中找到 New-SSHSession 但无法在 powershell 中加载
- android - Piccasso MVVM Rest Api:目标不能为空
- c#-8.0 - 为什么仍然可以将 null 分配给不可为 null 的引用类型?
- matrix - Prometheus 不会连接到 Synapse 指标
- linux - 如何在 Fedora 上安装 zenmap
- javascript - jquery如何映射到这段代码中的init函数
- python - 无法使用 PyGame 在顶部栏添加 ICON
- java - 我很好奇 Spring Boot 与 Apache Spark 数据集的集成
- html - 曲线在反应中没有粘在页面的最右边
- javascript - 在反应组件/随机数中使用useState随机更改两个div的状态