Manish Waran
Manish Waran

Reputation: 92

Guice @Inject not able to inject with multiple constructor

I will start with the over view of the problem that I am facing with an example.

class abstract A {
   @Inject
   A() {}

   @Inject
   A(A1 a1, A2 a2) {
      this.a1 =a1;
      this.a2 =a2;
   }
   public abstract doSomething();
   A1 a1;
   A2 a2;
}

class B extends A {

   @Inject
   A(A3 a3) {
      this.a3 =a3;
   }
   public doSomething() {
          System.out.println("some work");
   };
   A3 a3;
}
class C extends A {

   @Inject
   A(A4 a4) {
      this.a4 =a4;
   }
   public doSomething() {
          System.out.println("some work");
   };
   A4 a4;
}

Class B and C extends A using default constructor of A. So in class A, argument constructor is not invoked and the fields I want to be injected is null. I don't want to use field level @Inject. I want to use constructor injection. If that is not possible please provide with alternative solution.

Upvotes: 0

Views: 1946

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

Couple things here:

  • You can have at most one @Inject-annotated constructor per class.
  • Annotating with @Inject on abstract class doesn't make sense (it won't be instantiated anyway).
  • Your B and C are invoking no-args constructors because not specifying one is equivalent to calling super(). When you fix that (i.e. explicitly call super(a1, a2) with two arguments), you'd be good (and it doesn't have to do anything with dependency injection).

Upvotes: 1

Related Questions