You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Bean中如何正确注入List<Integer>而非List<String>集合?

问题根因

你配置中使用#{'4,6'.split(',')}生成的是字符串数组,转换为List后元素类型为String,和注入时声明的List<Integer>泛型不匹配。由于Java泛型擦除机制,注入阶段不会报错,只有在实际读取元素做类型强转(这里是做乘法运算时隐式强转)时才会抛出ClassCastException。

解决方案

方案1:在SpEL中直接转换元素类型为Integer

修改application-context.xml中testMap的entry配置,拆分字符串后将每个元素转为Integer:

<bean id="testMap" class="java.util.HashMap">
    <constructor-arg>
        <map key-type="java.lang.String" value-type="java.util.List">
            <entry key="test" value="#{'4,6'.split(',').stream().map(Integer::valueOf).toList()}" />
        </map>
    </constructor-arg>
</bean>

如果你的Spring版本不支持Java 8+的stream写法,可以改用SpEL原生集合迭代语法:

<entry key="test" value="#{T(java.util.Arrays).asList('4','6').!{T(java.lang.Integer).valueOf(#this)}}" />

方案2:显式声明List元素类型(适合固定值场景)

直接嵌套<list>标签并指定元素类型,可读性和稳定性更高:

<bean id="testMap" class="java.util.HashMap">
    <constructor-arg>
        <map key-type="java.lang.String" value-type="java.util.List">
            <entry key="test">
                <list value-type="java.lang.Integer">
                    <value>4</value>
                    <value>6</value>
                </list>
            </entry>
        </map>
    </constructor-arg>
</bean>

两种方案修改后,注入的testMap中List元素就会是Integer类型,执行乘法运算不会再触发类型转换异常。

内容的提问来源于stack exchange,提问作者marxmit7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:54:04