【问题标题】:How to use @ConfigurationProperties with Kotlin如何在 Kotlin 中使用 @ConfigurationProperties
【发布时间】:2019-11-30 19:48:41
【问题描述】:

我有这个自定义对象:

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 我已经完成了这个,但是我看不到这里缺少什么。

【问题讨论】:

  • 既然 Kotlin 已经有了Pair,为什么还要编写自己的Pair?为什么使用模棱两可的名称firstsecond 进行配置?我认为这个问题来自XY Problem
  • 好吧,因为 Kotlin 的 Pair 我有同样的错误。所以我尝试自己创建一个。但它呈现出相同的行为。我刚刚从原始Pair 复制。使用 Kotlin 的Pair,您有这种情况的工作案例吗?

标签: spring kotlin configurationproperties


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2020-07-24
    • 2018-06-27
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多