Java – Dagger 2 instantiation on application components

Dagger 2 instantiation on application components… here is a solution to the problem.

Dagger 2 instantiation on application components

I have a question about dagger2

If I provide an ApplicationComponent for @Singleton but don’t instantiate the object with @Inject in some class. Is the object instantiated or is it instantiated when it is @Inject in a class?
For example, in the code below, the test is 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

In this case, Test will be instantiated in the Main class by an instance of the DaggerComponent in that class.

However, in the Main2 class, Test is not instantiated unless an explicit @Inject annotation is marked on a property of type Test.

Also, note that in the above case, if you need to use a singleton instance of class Test in both classes Main and Main2, inject the Test object in both classes using the same DaggerComponent instance. When you instantiate a DaggerComponent in two classes, you get separate instances of class Test in Main and Main2.

If you want to see how Dagger uses scopes behind the scenes, read the code generated by Dagger. I wrote an article on medium about how Dagger scopes work internally. Follow this if you wish. How Dagger scopes work internally

Related Problems and Solutions