简体   繁体   中英

problem with injecting abstract class in spring

I have two abstract classes

class abstract A {
//some methods .
}

class abstract B extends A {
 private  C  c ;
//other methods
}

Spring config file :

<bean id="b" class="B" abstract="true">
    <property name="c" ref="C" />   //I have reference for C else where
</bean>

When I run the program , the class c is not getting injected . It is coming as null . Am i missing something ?

abstract=true means that the bean specification is a 'template' for other bean declarations to extend, it does not mean the class is abstract. I suspect bean with id b is not being created since it is a template/abstract definition. Remove abstract=true and make B a concrete type and it should work.

Documentation here: http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-child-bean-definitions

Although the use of 'abstract="true"' is not meant to indicate that the bean specification is for an abstract class, it is still required for an abstract class bean definition so that pre-instantiation is not attempted on that class (which would fail for an abstract class). This is indicated in a note below the section that the above link points to (http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-child-bean-definitions). If this were a situation where the super class was not an abstract class, then yes, 'abstract="true"' should not be used.

You don't show a setter for C in the abstract class B. You must use either setting or constructor injection. The code as posted can't work.

You should also specify B as the parent bean for C; likewise A for B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM