Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register custom configuration properties converter @ConfigurationPropertiesBinding

In Spring Boot project, the configuration in the YML file can be automatically converted to an @ConfigurationProperties annotated bean. But I need to override behavior to make non standard conversion because I inject value from environmental variable (which is a sting) but it should be AS map.

There is error

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'app.push.firebase.application-keys' to java.util.Map<com.example.services.push.service.api.model.kafka.Application, java.lang.String>:

    Property: app.push.firebase.application-keys
    Value: "{"applicationOne": "api=key-one","applicationTwo": "api=key-two"}"
    Origin: class path resource [application-local.yml] - 47:25
    Reason: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<com.example.services.push.service.api.model.kafka.Application, java.lang.String>]

My application.yml

app:
  use-dev-apns: true
  kafka.consumer.group: 'local'
  push:
    errorCallbackUrl: 'callback-url'
    firebase:
      applicationKeys:  '{"applicationOne": "api=key-one","applicationTwo": "api=key-two"}'
      defaultKey: 'api-key'

My property class


@ConstructorBinding
@ConfigurationProperties("app.push")
data class PushProperties(
    val errorCallbackUrl: String,
    val firebase: FirebaseProperties
)

data class FirebaseProperties(
    val applicationKeys: Map<Application,String>,
    val defaultKey: String
)

And custom converter


@ConfigurationPropertiesBinding
@Component
class StringToMapConverter: Converter<String, Map<Application, String>> {


    override fun convert(source: String): Map<Application, String> {
        try {
            val map = BasicJsonParser().parseMap(source) as Map<String, String>
            return  map.mapKeys { Application.valueOf(it.key.uppercase()) }
        } catch (e: JsonParseException) {
            throw Exception("app.callback-mappings property is invalid. Must be a JSON object string")
        }
    }
}

What could be the problem?

Custom converter bind data from string to Map<Application, String>

like image 613
Dmytro Fesyk Avatar asked Oct 21 '25 01:10

Dmytro Fesyk


1 Answers

I have solved the problem. The problem was that Kotlin Map class does not match the java.util.Map class. When I change Kotlin Map class to MutableMap class everything works correctly

like image 162
Dmytro Fesyk Avatar answered Oct 22 '25 21:10

Dmytro Fesyk