如何在Kotlin中使用@ConfigurationProperties

5

I have this custom object:

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,我已经完成了这个任务,但我无法看出还缺少什么。


为什么要自己编写Pair,而Kotlin已经有了一个?并且为什么要使用模糊的名称“first”和“second”来进行配置?我认为这个问题遭受了XY问题的困扰。 - ordonezalex
嗯,因为我使用 Kotlin 的 Pair 时遇到了同样的错误。所以我尝试自己创建一个,但是它表现出同样的行为。我只是从原始的 Pair 复制了一下。你有没有使用 Kotlin 的 Pair 成功应用于这个条件的案例呢? - rado
2个回答

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

1
另一个可能的解决方案是使用@ConstructionBinding注释。它将使用构造函数初始化属性,因此不需要默认值的可空性。
@ConstructorBinding
@ConfigurationProperties("my-properties")
class ComplexProperties (
    val pair: Pair
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接