繁体   English   中英

如何将 @ConfigurationProperties 与 Kotlin 一起使用

[英]How to use @ConfigurationProperties with Kotlin

我有这个自定义 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"

使用这个 class:

@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"

另一种可能的解决方案是使用@ConstructionBinding注释。 它将使用构造函数初始化属性,因此不需要默认值的可空性。

@ConstructorBinding
@ConfigurationProperties("my-properties")
class ComplexProperties (
    val pair: Pair
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM