Inject spring dependency in abstract super class

跟風遠走 提交于 2019-12-17 15:54:20

问题


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?


回答1:


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.




回答2:


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>



回答3:


Have an abstract parent bean:

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



来源:https://stackoverflow.com/questions/4238987/inject-spring-dependency-in-abstract-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!