如何在 Kotlin 中使用 @ConfigurationProperties

Gab*_*ado 5 spring kotlin configurationproperties

我有这个自定义对象:

data class Pair(
        var first: String = "1",
        var second: String = "2"
)
Run Code Online (Sandbox Code Playgroud)

现在我想用我的自动装配它application.yml

my-properties:
my-integer-list:
  - 1
  - 2
  - 3
my-map:
  - "abc": "123"
  - "test": "test"
pair:
  first: "abc"
  second: "123"
Run Code Online (Sandbox Code Playgroud)

使用这个类:

@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
    lateinit var myIntegerList: List<Int>
    lateinit var myMap: Map<String, String>
    lateinit var pair: Pair
}
Run Code Online (Sandbox Code Playgroud)

在添加之前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"
    }
}
Run Code Online (Sandbox Code Playgroud)

使用java我已经完成了这个,但是我看不出这里缺少什么。

小智 5

你不能用 Lateinit var 来做到这一点。

解决方案是将您的pair属性初始化为null:

@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
    ...
    var pair: Pair? = null
}
Run Code Online (Sandbox Code Playgroud)

或者使用默认值实例化您的对:

@Configuration
@ConfigurationProperties(prefix = "my-properties")
class ComplexProperties {
    ...
    var pair = Pair()
}
Run Code Online (Sandbox Code Playgroud)

您现在可以使用 application.yml 自动装配它:

...
pair:
  first: "abc"
  second: "123"
Run Code Online (Sandbox Code Playgroud)