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

如何在Spring XML配置中覆盖List等集合的默认实现?

How to Override Default Collection Implementations in Spring XML

Great question! You’re absolutely correct that Spring defaults to java.util.ArrayList for <list> tags, HashMap for <map>, and HashSet for <set> in XML configurations. The good news is Spring gives you straightforward ways to override these defaults—here’s how to do it for different collection types:

For List Collections

Use the list-class attribute on the <list> tag to specify your desired implementation. For example, to switch to LinkedList:

<bean id="myLinkedListBean" class="com.example.MyService">
    <property name="myList">
        <list list-class="java.util.LinkedList">
            <value>Item 1</value>
            <value>Item 2</value>
        </list>
    </property>
</bean>

For Map Collections

Similarly, use the map-class attribute on <map> to replace the default HashMap. Let’s use LinkedHashMap as an example:

<bean id="myLinkedHashMapBean" class="com.example.MyService">
    <property name="myMap">
        <map map-class="java.util.LinkedHashMap">
            <entry key="key1" value="value1"/>
            <entry key="key2" value="value2"/>
        </map>
    </property>
</bean>

For Set Collections

Use the set-class attribute on <set> to override the default HashSet. For a sorted TreeSet:

<bean id="myTreeSetBean" class="com.example.MyService">
    <property name="mySet">
        <set set-class="java.util.TreeSet">
            <value>Apple</value>
            <value>Banana</value>
            <value>Cherry</value>
        </set>
    </property>
</bean>

Using Custom Collection Implementations

If you have a custom class that implements java.util.List, java.util.Map, or java.util.Set, you can reference it directly via the same class attributes. Just make sure your custom collection has a no-argument constructor (Spring needs this to instantiate it):

<bean id="myCustomListBean" class="com.example.MyService">
    <property name="myCustomList">
        <list list-class="com.example.MyCustomList">
            <value>Custom Item 1</value>
            <value>Custom Item 2</value>
        </list>
    </property>
</bean>

Bonus: Annotation-Based Alternative

If you’re using Spring’s annotation-driven configuration instead of XML, you can directly return your preferred collection type in a @Bean method:

@Bean
public List<String> customLinkedList() {
    return new LinkedList<>(List.of("Item A", "Item B"));
}

This gives you full flexibility to use any collection implementation that fits your use case—whether it’s a standard JDK type or your own custom class.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:16:43