Why do we need it?

  • Used for common set of definitions across multiple beans
  • Inherit bean definition across other beans
  • Can be a bean itself
  • Can be an abstract bean, just to be overridden

Example

config.xml

<bean id="parentbean" class="...">
    <property name="commonPropertyName" value="commonValue" />
</bean>

<bean id="childA" class="..." parent="parentbean">
    <property name="childAPropertyName" value="childAValue" />
</bean>

<bean id="childB" class="..." parent="parentbean">
    <property name="childBPropertyName" value="childBValue" />
</bean>

childA and childB will both inherit the property definition commonPropertyName with a value of commonValue, but will each have their own properties as well.

Example with Lists

config.xml

<bean id="parentbean" class="...">
    <property name="mylist">
        <list>
            <value ref="dependentBean1" />
            <value ref="dependentBean2" />
        </list>
    </property>
</bean>

<bean id="childA" class="..." parent="parentbean">
    <property name="mylist">
        <list>
            <value ref="dependentBean3" />
        </list>
    </property>
</bean>

<bean id="childB" class="..." parent="parentbean">
    <property name="mylist">
        <list merge="true">
            <value ref="dependentBean4" />
        </list>
    </property>
</bean>

childA and childB will both inherit the mylist property containing dependentBean1 and dependentBean2.

However

  • childA will override the property values inherited with its single value of dependentBean3
  • childB will merge the inherited property values with dependentBean4

Making the Parent Bean Abstract

config.xml

<bean id="parentbean" class="..." abstract="true">
    <property name="mylist">
        <list>
            <value ref="dependentBean1" />
            <value ref="dependentBean2" />
        </list>
    </property>
</bean>

...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s