0

So I have a Parent class and multiple Child classes, such that the Parent class is not managed by Spring (no @Component annotation), but all Child classes are. The constructor of the parent class has some logic, and I need to add one more piece of logic to it, but it requires me to use a Spring Bean. What is the easiest way to do this?

Currently my child classes all use Constructor Injections, so one thing I can do is I can define the parameter in the constructor of the parent class, and in all child classes I can pass that parameter like so: super(newBean);

But this requires me to do a lot of copy pasting in each of the child class, is there a way I can avoid that?

PS: does this design raise any red flags for you guys?

mave_rick
  • 34
  • 8
  • of course it raises some flags for me at least, first time I see a Bean extending a non-bean – Eugene Aug 29 '18 at 11:36
  • well why specifically? I am simply defining some common logic that is common to all child classes. And I don't need an instance of the parent class – mave_rick Aug 29 '18 at 11:38
  • *And I don't need an instance of the parent class* - but you will get it anyway, the super constructor is called if you want it or not – Eugene Aug 29 '18 at 11:39
  • But this kind of pattern is super common isn't it. Take a look at this https://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor. If someone wants to use Spring to manage these instances, making the child classes `@Component`s makes sense right – mave_rick Aug 29 '18 at 11:42
  • are you saying that your Parent does some initialization based on some beans that are autowired in children? – Eugene Aug 29 '18 at 11:46
  • 1
    If you really need the dependency in your parent and its a non managed bean the only way to provide is through a constructor, so your `super(newBean)` should be the way to go. – Glains Aug 29 '18 at 11:48
  • Hey @Eugene, yes that's what I'm saying – mave_rick Aug 29 '18 at 11:55

0 Answers0