简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM