Friday, December 8, 2017

Spring Framework - 11 - Inheritance


Inheriting a parent Bean within the spring.xml

1)parent="<<parentBeanName>>" variable used within the <bean tag>
2)merge="true" used with the <list> tag of a child bean that inherits collections from a parent.. and adds additional objects to the existing list in the parent,

Example:

<?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> 

Java Code:
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());
        } 

Output when iterating over sets of parent/child would be:
 ---Elements in parent bean---
AAAA
BBBB
---Elements in child bean---
AAAA
BBBB
CCCC
DDDD 

Reference of the above code :
https://www.concretepage.com/spring/example_collection_merging_spring


____________________________________________________________________________

No comments:

Post a Comment