How to Merge Collections in Spring?

In my previous post I have explained about how to use collections in Spring. This tutorial explains how to merge collections or inherit the values from the parent bean. In some scenarios we need to define a bean as abstract using the abstract=true in the bean definition. It means that another bean definition will be child for this parent bean and will inherit all its properties. This is very useful when we have a common behavior which is used by most of the implementations. In that scenario, spring provides option to merge or inherit the collections which is defined in the parent bean. For example : If you define a List in your parent bean A, another child bean B can point bean A as parent and inherit all the list values defined in that bean.

There are some limitations on merging two collections. We can not merge two different types of collections. For example : we can not merge List and Set. This merging feature is available from Spring 2.0 on wards.


Look at the below example :

1. Create a Parent Bean


import java.util.List;

public class Company {
	private List<String> employees;

	public List<String> getEmployees() {
		return employees;

	public void setEmployees(List<String> employees) {
		this.employees = employees;

2. Define Child Bean and Parent Bean in the Spring Configuration


<beans xmlns=""

	<context:component-scan base-package=""/>
	<bean id="companyBean" abstract="true" class="">
		<property name="employees">
				<value>Employee 1</value>
				<value>Employee	2</value>
	<bean id="companyBeanChild" parent="companyBean">
		<property name="employees">
			<list merge="true">
				<value>Employee	3</value>
				<value>Employee	4</value>

3. Load Spring Configuration



public class SpringContextLoader {
	public static void main (String args[]){
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("javabeat/net/core/ioc/spring-beans-ioc.xml");
		Company company = (Company)applicationContext.getBean("companyBeanChild");

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!