Search code examples
javadependency-injectionguicelombok

Inject constructor dependency using Lombok Builder


I have a class file as below

import com.google.inject.Inject;
import lombok.Builder;

@Builder
public class A {
  private final B objB;
  private final C objC;

  @Inject
  public A(B b, C c) {
     this.objB = b;
     this.objC = c;
  }
}

Now if I have to use this object in another class, will the .builder() method takes care of the dependencies being injected.

 public class Main {
    public void doSomething() {
       A a = A.builder().build();
       a.getObjB(); // Will it be null ?
       a.getObjC(); // Will it be null ?

Solution

  • Injection always only works when you let guice deal with instance creation.

    So when you use

    @Inject
    private A a;
    

    guice will find that it needs a B and a C to create A and inject it.

    But when you instantiate A yourself, it does not matter if via new or via builder() guice does not know about the instance creation, thus in your example, B and C will be null.