Saturday, March 19, 2011

Spring : Inheritance between beans

Its obvious that inheritance help us reuse common behaviour across. From spring perspective, those beans which share common set of dependencies, will share a common base class.

Example : All repository classes require a DataSource, so instead of declaring the datasource again and again, we can have a base class containing the DataSource.

Consider the following classes :

Let us define a base class :

import javax.sql.DataSource;

public abstract class BaseRepository {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;

public DataSource getDataSource() {
return dataSource;


Now suppose one class just extends it :

public class FlightRepositoryImpl extends BaseRepository implements FlightRepository {

Now for spring handling this dependency we use 2 attributes : abstract and parent

<import resource="db-config.xml" />

<!-- set the parent/child relationship by abstract -->
<bean id="baseRepo" class="common.BaseRepository" abstract="true">
<property name="dataSource" ref="ds" />

<!-- set the parent/child relationship by refering to the parent bean -->
<bean id="flightRepo" class="com.XXX.FlightRepositoryImpl" parent="baseRepo" />

No comments:

Post a Comment