简体   繁体   English

关于应用程序组件的Dagger 2实例化

[英]Dagger 2 instantiation on application component

I have a question with dagger2, 我对dagger2有疑问,

If I provide @Singleton with ApplicationComponent but don't instantiate the object using @Inject in some class. 如果我使用ApplicationComponent提供@Singleton但是在某些类中不使用@Inject实例化该对象。 Does the object get instantiate or it will get instantiated when it is @Inject in some class? 对象是实例化还是在某些类中是@Inject时会被实例化? For example, in below code, does test instantiated on main2? 例如,在下面的代码中,是否在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 . 在上面的例子中,Test将在类Main中由该类中的DaggerComponent实例实例化。

But in class Main2 , Test will not be instanciated unless an explicit @Inject annotation is marked on a property of type Test . 但是在Main2类中,除非在Test类型的属性上标记显式的@Inject注释,否则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 . 另请注意,在上述情况下,如果在Main和Main2类中都需要类Test的单例实例,请使用相同的DaggerComponent实例在两个类中注入Test对象。 As you are separately instanciating DaggerComponent in both classes , you will get separate instances of class Test in Main and Main2. 由于您在两个类中单独实例化DaggerComponent,因此您将在Main和Main2中获得类Test的单独实例。

If you want to know how dagger uses scopes behind the scenes, read the Dagger generated code . 如果您想知道dagger如何在幕后使用示波器,请阅读Dagger生成的代码。 I have written an article on medium regarding how dagger scopes works internally. 我在介质上写了一篇关于匕首范围如何在内部工作的文章。 Follow this if you want to . 如果你愿意,请按照这个。 How Dagger scopes work internally Dagger范围如何在内部工作

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: 您可以通过dagger检查生成的代码,以获取DaggerComponent类的inject(main2)方法,它将为空,如下所示:

   @Override
     public void inject(main2 clazz) {}

Whereas the inject(main) method will have calls to inject the field (after creating an instance of it). inject(main)方法将调用注入字段(在创建它的实例之后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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