Spring Collection Merging Example
November 04, 2021
The Spring container supports merging collections. We can create a parent element using <list/>
, <map/>
, <set/>
or <props/>
elements and they can have child <list/>
, <map/>
, <set/>
or <props/>
elements overriding values from the parent collection. The elements in child collection are the result of merging the elements of the parent and child collections.
Merging parent and child collections can be controlled by
merge
property. The value merge="true"
will allow child collection to inherit parent collection.
Collection Merging Example
spring-config.xml<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="parentCollection" class="com.concretepage.bean.MyCollection"> <property name="mySet"> <set> <value>AAAA</value> <value>BBBB</value> </set> </property> </bean> <bean id="childCollection" parent="parentCollection"> <property name="mySet"> <set merge="true"> <value>CCCC</value> <value>DDDD</value> </set> </property> </bean> </beans>
package com.concretepage.bean; import java.util.Set; public class MyCollection { private Set<String> mySet; public Set<String> getMySet() { return mySet; } public void setMySet(Set<String> mySet) { this.mySet = mySet; } }
SpringDemo.java
package com.concretepage; import java.util.Iterator; import java.util.Set; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.concretepage.bean.MyCollection; public class SpringDemo { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); MyCollection myCollection=(MyCollection)context.getBean("parentCollection"); //access parent collection System.out.println("---Elements in parent bean---"); Set<String> parentSet=myCollection.getMySet(); Iterator<String> itrP= parentSet.iterator(); while(itrP.hasNext()){ System.out.println(itrP.next()); } MyCollection concreteChild=(MyCollection)context.getBean("childCollection"); //access child collection System.out.println("---Elements in child bean---"); Set<String> setC=concreteChild.getMySet(); Iterator<String> itrC= setC.iterator(); while(itrC.hasNext()){ System.out.println(itrC.next()); } context.close(); } }
---Elements in parent bean--- AAAA BBBB ---Elements in child bean--- AAAA BBBB CCCC DDDD