You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从application.yml读取Kotlin Pair列表到MutableList

解决Spring Boot Kotlin项目中YAML绑定MutableList<Pair<String, Int>>的问题

Spring Boot默认不支持直接将YAML配置绑定到Kotlin的Pair<String, Int>类型,因为其类型转换系统没有内置对Kotlin Pair的解析逻辑。以下是两种可行的解决方案:

方案1:调整YAML格式并利用构造函数绑定(推荐)

这种方式无需额外编写转换器,仅需调整配置格式和配置类的写法:

  1. 修改application.yml配置
    将每个Pair以键值对形式定义,对应Pair的first和second属性:
user-parameters:
  knapsacks:
    - first: James
      second: 102
    - first: Mary
      second: 185

或者使用更简洁的数组格式:

user-parameters:
  knapsacks:
    - ["James", 102]
    - ["Mary", 185]
  1. 调整配置类,启用构造函数绑定
    Spring Boot 2.2及以上版本支持@ConstructorBinding,通过构造函数直接注入配置值,适配Kotlin的不可变类型特性:
@Configuration
@ConfigurationProperties(prefix = "user-parameters")
@ConstructorBinding
class UserParameters(
    val knapsacks: MutableList<Pair<String, Int>>
) {
    init {
        // 这里保留你的初始化逻辑
    }
}
  1. 开启配置属性扫描
    在Spring Boot主类上添加@ConfigurationPropertiesScan注解,确保Spring能扫描到该配置类:
@SpringBootApplication
@ConfigurationPropertiesScan
class YourApplication

fun main(args: Array<String>) {
    runApplication<YourApplication>(*args)
}

方案2:自定义类型转换器

如果不想修改配置类的结构,可以编写自定义转换器,让Spring能够将YAML中的条目转换为Pair类型:

  1. 编写转换器类
    创建一个实现Converter接口的组件,负责将YAML中的数组转换为Pair<String, Int>:
import org.springframework.core.convert.converter.Converter
import org.springframework.stereotype.Component

@Component
class StringIntPairConverter : Converter<List<Any>, Pair<String, Int>> {
    override fun convert(source: List<Any>): Pair<String, Int> {
        require(source.size == 2) { "每个背包配置必须包含所有者和容量两个元素" }
        val owner = source[0] as String
        val capacity = source[1] as Int
        return Pair(owner, capacity)
    }
}
  1. 使用数组格式的YAML配置
    和方案1中的数组格式一致,Spring会自动使用上述转换器处理每个数组条目:
user-parameters:
  knapsacks:
    - ["James", 102]
    - ["Mary", 185]
  1. 保留原配置类
    无需修改原配置类的结构,Spring会自动识别并应用转换器:
@Configuration
@EnableAutoConfiguration
@ConfigurationProperties(prefix = "user-parameters")
class UserParameters {
    var knapsacks = mutableListOf<Pair<String, Int>>()
    init {
        // 你的初始化逻辑
    }
}

内容的提问来源于stack exchange,提问作者user13099160

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:20:35