首页 > 解决方案 > Spring Boot是否可以将接口的实现绑定到@ConfigurationProperties

问题描述

今天是个好日子!

是否可以将接口作为Spring Boot应用程序的配置属性,以便 Spring Boot 可以根据对象属性选择实现?

例如,我有一个在yaml文件中描述的下一个外部化配置:

props:
    elements:
        - name: element1
          uniqueProperty1: value1
        - name: element2
          uniqueProperty2: value2

@ConfigurationProperties下一个用元素列表注释的类,实现Element接口,作为具有一些实现类的属性(Kotlin中的代码):

@ConfigurationProperties(value = "props")
class ConfigProperties() {
    var elements: List<Element> = emptyList()
}

interface Element {
    val name: String
}

class ElementImpl1 : Element {
    override val name: String = ""
    val uniqueProperty1: String = ""
}

class ElementImpl2 : Element {
    override val name: String = ""
    val uniqueProperty2: String = ""
}

当我运行我的应用程序时,会发生下一个错误: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'props.elements' to java.util.List<Element>

标签: javaspringspring-bootkotlin

解决方案


推荐阅读