Bean definition inheritance is a powerful feature of Spring Framework that allows developers to define a hierarchy of bean definitions in which child beans inherit configurations from their parent beans. It’s a convenient way to reduce code duplication and achieve modularity in Spring configurations.
To understand how bean definition inheritance works, let’s take an example of a simple Spring configuration. Assume we have two beans, ‘dataSource‘ and ‘transactionManager‘.
<bean id="dataSource" class="com.example.DataSource">
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
Here the ‘dataSource‘ bean defines the connection parameters and the ‘transactionManager‘ bean depends on ‘dataSource‘ for transaction management.
Now suppose we have more than one data source with the same configuration except for the URL. In this case, we can use bean definition inheritance to avoid duplicating the ‘dataSource‘ configuration. We can define a parent ‘dataSource‘ bean and sub-beans can inherit the configuration and override the URL property.
<bean id="parentDataSource" abstract="true" class="com.example.DataSource">
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>
<bean id="dataSource1" parent="parentDataSource">
<property name="url" value="jdbc:mysql://localhost/test1"/>
</bean>
<bean id="dataSource2" parent="parentDataSource">
<property name="url" value="jdbc:mysql://localhost/test2"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource1"/>
</bean>
Here the ‘parentDataSource‘ bean is defined with the common configuration options, and the sub-beans ‘dataSource1‘ and ‘dataSource2‘ override only the ‘url‘ property. The ‘abstract="true"` attribute in the ‘parentDataSource‘ bean definition indicates that it is a template bean and cannot be instantiated directly.
Note that bean definition inheritance can be used not only for data source configurations but also for any other type of bean definitions. It’s a powerful way of building modular and reusable Spring configurations.