Merging lists in a Spring configuration file

Spring provides useful types for creating lists of values. However, it is not as good for merging lists. Here is an option.

A list usually looks like this in a Spring configuration file:

<bean id="aList" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<value>a list element</value>
<value>another list element</value>
</list>
</property>
</bean>

Or, if you are the fun-loving type, you can write this as follows:

<util:list id="someList">
<value>a list element</value>
<value>another list element</value>
</util:list>

…as long as you provide the appropriate schema with xmlns:util="http://www.springframework.org/schema/util", as described in the Spring documentation.

What you cannot do, however, is merge two lists. You add can a list bean to your list, but it will only be considered as a separate item; it won’t be merged.

A solution is to provide a new Spring bean that supports lists.


package com.company.utils.spring;
import java.util.*;
import org.springframework.beans.factory.config.ListFactoryBean;
public class ListMergerFactory extends ListFactoryBean {
private final List listOfLists;
public ListMergerFactory(List listOfLists) throws Exception {
this.listOfLists = listOfLists;
setSourceList(new ArrayList());
}
protected Object createInstance() {
List listOrigin = (List) super.createInstance();
for (Iterator iter = listOfLists.iterator(); iter.hasNext();) {
List element = (List) iter.next();
listOrigin.addAll(element);
}
return listOrigin;
}
}

This will let you define a list as follows (I don’t have the source for this part anymore, so some details may be wrong):

<bean id="aList" class="com.company.utils.spring.ListMergerFactory">
<constructor-arg value="myOtherList"/>
<property name="sourceList">
<list>
<value>a list element</value>
<value>another list element</value>
</list>
</property>
</bean>

The downside is that you cannot use the util:list shortcut for defining a list that is made of another list.

About Eric Lefevre-Ardant

Independent technical consultant.
This entry was posted in spring. Bookmark the permalink.