28

I have requirement to inject dependency in abstract superclass using spring framework.

class A extends AbstractClassB{ 
    private Xdao daox ;
    ...
    public setXdao() { ... }
}

class AbstractClassB{
    ..
    private yDao  daoy;
    public seyYdao() { ... }
}

I need to pass superclass dependency everytime i instantiate Abstract class B (which can be subclassed in 100's of ways in my project)

entry in application.xml (spring context file)

<bean id="aClass" class="com.mypro.A" 
    <property name="daox" ref="SomeXDaoClassRef" /> 
    <property name="daoy" ref="SomeYDaoClassRef"/>
</bean>

How can i just create bean reference of super class AbstractClassB in application.xml so that i can use it in all subclass bean creation?

RishiKesh Pathak
  • 2,122
  • 1
  • 18
  • 24
bob
  • 281
  • 1
  • 3
  • 4

3 Answers3

37

You can create an abstract bean definition, and then "subtype" that definition, e.g.

<bean id="b" abstract="true" class="com.mypro.AbstractClassB">
    <property name="daox" ref="SomeXDaoClassRef" /> 
</bean>

<bean id="a" parent="b" class="com.mypro.A">
    <property name="daoy" ref="SomeYDaoClassRef" /> 
</bean>

Strictly speaking, the definition for b doesn't even require you to specify the class, you can leave that out:

<bean id="b" abstract="true">
    <property name="daox" ref="SomeXDaoClassRef" /> 
</bean>

<bean id="a" parent="b" class="com.mypro.A">
    <property name="daoy" ref="SomeYDaoClassRef" /> 
</bean>

However, for clarity, and to give your tools a better chance of helping you out, it's often best to leave it in.

Section 3.7 of the Spring Manual discusses bean definition inheritance.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • If my parent class is not abstract and it is concrete class then still is this valid by ignoring abstract=true in the parent and declaring only parent at child..? – Kanagavelu Sugumar May 10 '17 at 16:07
4

You can use the abstract flag of Spring to tell Spring that a class is abstract. Then all concrete implementations can simply mark this bean as their parent bean.

<bean id="abstractClassB" class="AbstractClassB" abstract="true">
  <property name="yDao" ref="yDao" />
</bean>

<bean id="classA" class="A" parent="abstractClassB">
  <property name="xDao" ref="xDao" />
</bean>
peakit
  • 28,597
  • 27
  • 63
  • 80
2

Have an abstract parent bean:

http://forum.springsource.org/showthread.php?t=55811

duffymo
  • 305,152
  • 44
  • 369
  • 561