Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java & Guice - How to deal with inheritance and abstraction?

In the following code is it required to annotate the constructor of my base class with "Inject"? what if the base class is an abstract class?

Is it required to call super in my constructor when using DI?

public class Base {

   @Inject
   public Base(IConfig config) {
      // Do stuff
   }
}

public class A extends Base {

   @Inject
   public A(IConfig config) {
      super(config);
   }
}
like image 242
aryaxt Avatar asked Feb 26 '12 08:02

aryaxt


1 Answers

Depends on what you want to bind. If you bind Base to A (bind(Base.class).to(A.class)), then yes, the second constructor and @Inject is needed, but the one on Base is not. If you plan to construct also Base, you need the @Inject.

Concerning the call to super(), Java needs it (this has nothing to do with Guice) if you have only a single constructor with IConfig. But nothing prevent you to remove it if you don't need to inject IConfig in Base.

like image 62
Laurent Grégoire Avatar answered Sep 28 '22 06:09

Laurent Grégoire