首页 > 解决方案 > 如何在 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 我已经完成了这个,但是我看不到这里缺少什么。

标签: springkotlinconfigurationproperties

解决方案


你不能用 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"

推荐阅读