Dcortez
Dcortez

Reputation: 4238

Spring - Inject proper service implementation in abstract class level autowired field

I have 2 class hierarchies:

* ClassA
  * ClassB

* AbstractClass
  * Class1
  * ...
  * Class5

AbstractClass autowires ClassA as follows:

public abstract class AbstractClass {

    @Autowired
    protected ClassA classA;
}

Now I would like to inject ClassA into Class1, .., Class4 implementations but ClassB into Class5. I'm aware that I can do that by injecting directly in implementing classes rather than in abstract class (as in Similar Question) but that means that I have to have the same field declared not once but five times. Additionally if I want to use this field in abstract class I would have to enforce creating getter in implementing class and use it to get that service. It works but it doesn't seem to me like right way to do it.

Upvotes: 1

Views: 682

Answers (1)

11thdimension
11thdimension

Reputation: 10633

Here's one way to do it

@Component
class ClassA {}

@Component
class ClassB extends ClassA {}

abstract class AbstractClass {
    protected ClassA classA;
}

@Component
class Class1 extends AbstractClass {
    public Class1(ClassA classA) {
        this.classA = classA;
    }
}
//... Same for Class2/3/4

@Component
class Class5 extends AbstractClass {
    public Class5(ClassB classB) {
        this.classA = classB;
    }
}

This lets you have the common property and methods in the abstract class and if qualify them in the child classes using constructor injection

Upvotes: 1

Related Questions