0

If I had an abstract class that was inherited by many other classes, would @Inject be alright on a protected object to use it in the children classes ?

Here is a shortened example:

Abstract class inherited from:

import javax.inject.Inject;
//Many imports
public abstract class FatherMessageHandler{

    //All the neeeded code...
    @Inject
    protected MyMessageHandler messageHandler;
}

One of the child class:

public class UseMessageHandler extends FatherMessageHandler {

        //All the neeeded code...
          MyMessageHandler.getMessageAlert();
}

Is it good practice to do so ? Is it a no go ? Or is there a cleaner way ? I'm asking this as I'm quite new to injections !

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Youri
  • 442
  • 5
  • 15
  • 2
    DI is better on constructors as it eases unit tests. – Arnaud Denoyelle Mar 12 '19 at 09:43
  • 2
    Field injection is obsolete and discouraged, i.e. you should probably use it only for legacy code where it's too expensive to change injection approach. See [this answer](https://stackoverflow.com/a/39892204/4494577) for details. – jannis Mar 12 '19 at 09:52
  • 2
    @jannis Indeed, this is a rather old code on a huge project which i'm working on as a junior, so there's not much we can change in the "injection approach" at this point. Thanks for the link, i'll make sure to read the thread ! – Youri Mar 12 '19 at 09:57

0 Answers0