简体   繁体   中英

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);
    }
}

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

But in class Main2 , Test will not be instanciated unless an explicit @Inject annotation is marked on a property of type Test .

Also , note that in case above , if you need singleton instance of class Test in both class Main and Main2 , use the same DaggerComponent instance to inject Test object in both class . As you are separately instanciating DaggerComponent in both classes , you will get separate instances of class Test in Main and Main2.

If you want to know how dagger uses scopes behind the scenes, read the Dagger generated code . I have written an article on medium regarding how dagger scopes works internally. Follow this if you want to . How Dagger scopes work internally

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM