【问题标题】:Kotlin Spring boot @ConfigurationProperties for listKotlin Spring boot @ConfigurationProperties 用于列表
【发布时间】:2018-06-27 18:30:39
【问题描述】:

我想使用 Kotlin 读取 yaml 配置文件,下面是我的代码: application.yml

message:
  messages:
    - name: abc
      type: aaa
      size: 10
    - name: xyz
      type: bbb
      size: 20

MessageConfig.kt

package com.example.demokotlin

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Configuration
import java.math.BigDecimal

@ConfigurationProperties(prefix = "message")
@Configuration
class MessageConfig {
  lateinit var messages: List<Message>
}

class Message {
  lateinit var name: String
  lateinit var type: String
  lateinit var size: BigDecimal
}

使用配置的类:

package com.example.demokotlin

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class MessageService @Autowired constructor(private var messageConfig: MessageConfig) {

  fun createMessage(): String {
    println("in service........")
    println(messageConfig.messages[0].name)
    println(messageConfig.messages[0].type)
    println(messageConfig.messages[0].size)
    return "create a message......."
  }
}

看起来如果 yaml 文件有数组/列表,Kotlin 无法正确读取它,但它可以在没有数组的情况下工作。

我有完全相同的代码并且适用于 Java。我的 Kotlin 代码有问题吗?

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    您遇到了这个bug。简单的改变

    lateinit var messages: List<Message>
    

    var messages: MutableList<Message> = mutableListOf()
    

    使您的代码工作。 Here is a full working example

    编辑(2019 年 3 月):

    As of SB 2.0.0.RC1 and Kotlin 1.2.20, you can use lateinit or a nullable var.

    Docs

    编辑(2020 年 5 月):

    As of SB 2.2.0 你可以使用@ConstructorBinding@ConfigurationPropertiesdata class 上设置val 属性。

    以原来的类为例,现在可以这样写:

    @ConstructorBinding
    @ConfigurationProperties(prefix = "message")
    data class MessageConfig(val messages: List<Message>) {
      data class Message(
        val name: String,
        val type: String,
        val size: BigDecimal
      )
    }
    

    【讨论】:

    • 这个答案对我帮助很大。谢谢。
    • 在 Kotlin 1.3.11 和 springboot 2.10 中已修复,MessageConfig.kt 中提供的示例现在可以使用
    • working example 真的对我有用。最后一个edit (May 2020) 没有。非常感谢。
    【解决方案2】:

    在带有 spring-boot 2.10 的 Kotlin 1.3.11 中已修复,MessageConfig.kt 中提供的示例现在可以使用

    @PropertySource("classpath:application.yml")
    @ConfigurationProperties(value = "message")
    class MessageConfig {
      lateinit var messages: List<Message>
    }
    
    class Message {
      lateinit var name: String
      lateinit var type: String
      lateinit var size: BigDecimal
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2021-03-31
      • 2015-06-17
      • 2016-07-24
      • 2019-11-22
      • 1970-01-01
      相关资源
      最近更新 更多