1

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.

2
  • You can use constructor injection in the child classes Commented Nov 23, 2017 at 13:24
  • Could you show example as an answer? So if it works I could accept it? Commented Nov 23, 2017 at 13:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Definitely looks better and allows for direct access to service in the upper class. Thanks for help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.