Home > database >  Spring Boot Kotlin - Injecting a map from a YAML file
Spring Boot Kotlin - Injecting a map from a YAML file

Time:12-18

test.yml (location: resources/properties/)

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
    }

}

I want to receive the values below edit as a map.

I tried options for @ConfigurationProperties with prefix and value, but it doesn't work.

If I use properties file, it works well, but not yml file.

What am I missing? Thanks.

kotlinVersion = '1.6'; springBootVersion = '2.6.1'

CodePudding user response:

Something like this (without @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)
    }
}

Output:

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

CodePudding user response:

You are missing the @ContructorBinding annotation (required as of Spring Boot 2.2.0). Please see this answer:


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

If you wanna use a non-standard yml file (not called application.yml or derivate), like in the example you provided, then you need to add also the @PropertySource annotation to your Configuration data class.


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