Inject spring dependency in abstract super class

后端 未结 3 1693
忘了有多久
忘了有多久 2020-12-05 13:41

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

class A extends AbstractClassB{ 
    private Xdao daox ;
    ...
    p         


        
相关标签:
3条回答
  • 2020-12-05 14:10

    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.

    0 讨论(0)
  • 2020-12-05 14:19

    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>
    
    0 讨论(0)
  • 2020-12-05 14:22

    Have an abstract parent bean:

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

    0 讨论(0)
提交回复
热议问题