【问题标题】:Spring Boot Kotlin - Injecting a map from a YAML fileSpring Boot Kotlin - 从 YAML 文件中注入地图
【发布时间】:2022-01-20 04:52:52
【问题描述】:

test.yml(位置:资源/属性/)

edit:
  field1: test
  field2: test
  field3: test
  field4: test

PropertyConfig.kt

@Configuration
@PropertySource("classpath:properties/test.yml")
class PropertyConfig {

    @Bean
    @ConfigurationProperties(prefix = "edit")
    fun testProperty() = mutableMapOf<String, String>()

}
@Service
class EditService(
    private val testProperty: Map<String, String>
) {

    fun print() {
        println(testProperty) // empty
    }

}

我想接收下面编辑的值作为地图。

我尝试了带有前缀和值的 @ConfigurationProperties 选项,但它不起作用。

如果我使用属性文件,它工作得很好,但不是 yml 文件。

我错过了什么?谢谢。

kotlinVersion = '1.6'; springBootVersion = '2.6.1'

【问题讨论】:

  • 您是否还添加了:@EnableConfigurationProperties(YourConfigPropClass::class) @ConfigurationPropertiesScan 在您的 Application Main 顶部?

标签: spring-boot kotlin dependency-injection yaml properties-file


【解决方案1】:

类似这样的东西(没有@Bean):

@ConfigurationProperties(prefix = "") // blank since "edit:" is root element
@ConstructorBinding
data class EditProperties(
    val edit: Map<String, String> // property name must match to relevant root element in YAML
)

@Service
class EditService(private val properties: EditProperties) {

    fun print() {
        println(properties.edit)
    }
}

输出:

{field1=test, field2=test, field3=test, field4=test}

【讨论】:

    【解决方案2】:

    您缺少 @ContructorBinding 注释(从 Spring Boot 2.2.0 开始需要)。请看this answer:

    
        @ConstructorBinding
        @ConfigurationProperties("")
        data class PropertyConfig(
                val edit: Map<String,String>
         )
    

    如果您想使用非标准 yml 文件(不称为 application.yml 或派生文件),就像您提供的示例中一样,那么您还需要将 @PropertySource 注释添加到您的配置数据类中。

    
        @ConstructorBinding
        @ConfigurationProperties("")
        @PropertySource(value = "classpath:test.yml")
        data class PropertyConfig(
                val edit: Map<String,String>
         )
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 2014-09-15
      • 2017-08-23
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2019-12-15
      • 2019-03-18
      相关资源
      最近更新 更多