Kotlin中使用@Value注⼊application.properties内的Map<String,String>配置
Kotlin Spring 项目使用@Value注入Map类型配置实现方案
1. 配置文件编写
在application.properties中按照SpEL支持的键值对格式定义Map:
# 示例Map配置,键值对用大括号包裹,字符串值建议用引号包裹避免解析错误 my.custom.config={username:"admin",password:"123456",env:"prod"}
2. 代码注入实现
有两种常用注入方式,优先推荐构造注入:
构造注入(推荐)
import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component @Component class CustomConfigService( // SpEL表达式说明:#{} 标记为SpEL解析,${} 读取配置文件的占位符 @Value("#{\${my.custom.config}}") val configMap: Map<String, String> ) { // 后续直接使用configMap即可 fun printConfig() { configMap.forEach { (k, v) -> println("$k -> $v") } } }
字段注入
import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component @Component class CustomConfigService { @Value("#{\${my.custom.config}}") lateinit var configMap: Map<String, String> }
3. 常见问题处理
- 配置不存在时给默认空Map:把注解改为
@Value("#{\${my.custom.config:{:}}}"),启动时如果找不到对应配置会自动注入空Map,避免启动失败 - 值包含特殊字符:如果配置值有空格、逗号、特殊符号,必须用引号包裹,示例:
my.custom.config={desc:"测试 配置,带特殊字符"} - YAML格式适配:如果用
application.yml,需要把Map配置用单引号包裹,避免被YAML自身解析:my: custom: config: '{"username":"admin","password":"123456","env":"prod"}'
内容的提问来源于stack exchange,提问作者Adey
相关产品推荐
相关产品推荐

