在Spring Boot项目中,YML文件中的配置可以自动转换为@ConfigurationProperties注释的bean。但我需要覆盖行为来进行非标准转换,因为我从环境变量中注入值(这是一个刺痛(,但它应该是AS映射。
出现错误
***************************
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>]
我的应用程序.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'
我的房产类别
@ConstructorBinding
@ConfigurationProperties("app.push")
data class PushProperties(
val errorCallbackUrl: String,
val firebase: FirebaseProperties
)
data class FirebaseProperties(
val applicationKeys: Map<Application,String>,
val defaultKey: String
)
和自定义转换器
@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")
}
}
}
可能是什么问题?
自定义转换器将数据从字符串绑定到Map<应用程序,字符串>
我已经解决了这个问题。问题是KotlinMap类与java.util.Map类不匹配。当我将Kotlin Map类更改为MutableMap类时,一切正常