Search code examples
javaandroiddagger

Dagger 2 instantiation on application component


I have a question with dagger2,

If I provide @Singleton with ApplicationComponent but don't instantiate the object using @Inject in some class. Does the object get instantiate or it will get instantiated when it is @Inject in some class? For example, in below code, does test instantiated on main2?

@Singleton
public class Test {
    @Inject
    public Test() {
    }
}


public class main() {

    @Inject Test test;

    public void start() {
        DaggerComponent.create().inject(this);
    }
}

public class main2() {
    public void start() {
        DaggerComponent.create().inject(this);
    }
}

Solution

  • It will get instantiated when it is injected in some class.

    You can check the generated code by dagger for the inject(main2) method for your DaggerComponent class and it will be empty like this:

       @Override
         public void inject(main2 clazz) {}
    

    Whereas the inject(main) method will have calls to inject the field (after creating an instance of it).