0

Can we use abstract class to just hold common member variables which are autowired. This was the classes extending the abstract class need not declare the member fields again. Is this a good design pattern ? If not what is a better way to achieve this ? Note : The abstract class does not have any methods.

abstract class Abs {  

    @autowired
    protected ClassA varA;  
    @Autowired
    protected ClassB varB;  
    @Autowired
    protected ClassC varC;  
    ...  
}

class My1 extends Abs {  

    public void methodA() {  
        //make call  
        varA.aCall()  
        varB.bCall()  
        varC.cCall()  
    }
Paul Richter
  • 10,908
  • 10
  • 52
  • 85
Thunderhashy
  • 5,291
  • 13
  • 43
  • 47

1 Answers1

0

Since you said in a comment that "The only reason for the abstract class is to hold common shared member variables", there is no reason for you to use abstract class inheritance for this purpose. If there were no requirement for the vars to be autowired, I would say declare them as public static final in an interface, which needs not be implemented as you could just reference them statically. Since they do need to be autowired, and you cannot autowire static variables, I suggest putting them in a bean dedicated to holding variables and have that bean as a local variable in each class that needs them, where you were going to use abstract inheritance. This conforms to the pattern of composition, which is a more lightweight alternative to inheritance.

Community
  • 1
  • 1
amphibient
  • 29,770
  • 54
  • 146
  • 240