user3138596
user3138596

Reputation: 81

Spring beans understanding

What is the use of extends and parent attributes in spring bean file. Is it related to a class extending another class. If some could share some thoughts around this it would be great. Some linke and examples would also be helpful.

Upvotes: 1

Views: 88

Answers (1)

Andrei
Andrei

Reputation: 3106

The abstract and parent mechanism is used to keep your XML configuration DRY (Don't Repeat Yourself).

Consider you have 2 beans with 3 similar properties and 2 distinct.

Instead of repeating those 3 similar properties in both beans, you can do this:

  • make a bean that is abstract and holds those 3 common properties.
  • set the parent attribute on your 2 beans, to point to the abstract bean.

An example would be here.

<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="BaseCustomerMalaysia" class="com.mkyong.common.Customer" abstract="true">
        <property name="country" value="Malaysia" />
    </bean>

    <bean id="CustomerBean" parent="BaseCustomerMalaysia">
        <property name="action" value="buy" />
        <property name="type" value="1" />
    </bean>

</beans>

Upvotes: 3

Related Questions