SpEL中列表型Map的格式是什么?如何通过@Value读取配置对应值?
问题解决方法
方案1:调整SpEL表达式适配@Value读取
你遇到的报错本质是Spring解析SpEL时对嵌套集合的默认类型推断不符合预期,你可以选两种修改方式:
- 改application.properties的配置项,显式声明value为List类型:
map-of-lists={'KEY1':T(java.util.Arrays).asList('value1','value2'),'KEY2':T(java.util.Arrays).asList('value3','value4'),'KEY3': T(java.util.Arrays).asList('value5')}
修改后原有@Value("#{${map-of-lists}}") final Map<String, List<String>> mapOfLists的写法可以直接正常运行。
2. 不改配置,调整@Value的SpEL表达式,显式做类型转换:
@Value("#{${map-of-lists}.entrySet().stream().collect(java.util.stream.Collectors.toMap(Map.Entry::getKey, e -> new java.util.ArrayList<>(e.getValue())))}") private Map<String, List<String>> mapOfLists;
方案2:使用@ConfigurationProperties(更推荐)
这是Spring官方推荐的复杂类型配置读取方案,类型安全,无需写复杂SpEL,维护成本更低:
- 首先定义配置绑定类:
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; import java.util.Map; @ConfigurationProperties(prefix = "custom") public class CustomProperties { private Map<String, List<String>> mapOfLists; public Map<String, List<String>> getMapOfLists() { return mapOfLists; } public void setMapOfLists(Map<String, List<String>> mapOfLists) { this.mapOfLists = mapOfLists; } }
- 在启动类或任意配置类上添加注解启用配置绑定:
@EnableConfigurationProperties(CustomProperties.class)
- 调整application.properties写法,结构更清晰:
custom.map-of-lists.KEY1[0]=value1 custom.map-of-lists.KEY1[1]=value2 custom.map-of-lists.KEY2[0]=value3 custom.map-of-lists.KEY2[1]=value4 custom.map-of-lists.KEY3[0]=value5
- 业务代码中直接注入配置类即可使用:
@Autowired private CustomProperties customProperties; // 取值:customProperties.getMapOfLists()
@Value读取列表型Map的适用性判断
该方案不合适,仅适合临时调试使用,正式项目不推荐:
- @Value原生适合读取单个简单类型配置,读取复杂嵌套集合需要手写复杂SpEL,可读性差,出错概率高
- 无提前类型校验,配置格式错误只有运行时才会抛出异常
- 相比之下@ConfigurationProperties支持搭配
@Validated做参数校验,对多环境、配置中心的适配性也更好,是复杂类型配置的首选方案。
内容的提问来源于stack exchange,提问作者Tarun Kolla
相关产品推荐
相关产品推荐

