inject beans into an abstract class with spring and java ee 5

user1414745 picture user1414745 · May 14, 2013 · Viewed 10.5k times · Source

I am injecting a spring-managed bean into an abstract class and it seems that it doesn't work. Here is an explanation of what I do, if it is not enough, I can edit the post and add some code:

  1. implement the java code - 1 abstract class, 2 classes that inherit from it and the bean to be injected and used in the abstract class and thus by the subclasses.
  2. define the bean in the spring config.
  3. define the abstract class and 2 subclasses in the spring config.
  4. define the first bean as a property of the abstract class bean.

result - it's not working.

Then I tried to move the injected bean from the abstract class into the two subclasses. Now it works.

So, did I do something wrong, or is it theoretically impossible to inject a bean into an abstract class with spring 3 and Java EE 5?

Answer

Ravi K Thapliyal picture Ravi K Thapliyal · May 14, 2013

Is it theoretically impossible to inject a bean into an abstract class with spring 3 and Java EE 5?

Dependency Injection happens on an Object not its Class. Spring injects dependencies into managed beans which are Objects already instantiated by Spring. Since, an Abstract Class cannot be instantiated it would be conceptually wrong to think about DI here.

On a somewhat related note, you can also define a non-abstract Class as an abstract Spring bean by adding the attribute abstract=true to the <bean> tag. This indicates that the bean would not be instantiated and would serve as a mere template of properties that other beans can use through bean inheritance (which isn't related to Java inheritance at all).

In this context as well, (if you've configured it) the Dependency Injection would only happen for the child beans and not their parent bean since it has been defined as abstract. (Note: It's not mandatory for the parent bean to be abstract but it makes sense to do so when all it does is to act as a set of common bean properties.)