繁体   English   中英

如何使用Dagger2在其构造函数中使用args注入对象

[英]How to inject object with args in it's constructor with Dagger2

更新

现在,我像这样修改了我的代码,它可以工作,但是我不知道这是正确的方法。

该课程 http://pastebin.com/srhu4eB7

这是注射 http://pastebin.com/wLbxBQqb

我正在学习如何在我的项目中使用dagger2,但是我不知道如何注入这种依赖性。 我有一个带有构造函数的测试函数,必须在其中传递3个参数,这些参数来自要向其注入类的活动。 这是我的测试课程http : //pastebin.com/XqRNFbvj这是我的测试课程模块http : //pastebin.com/r4wmqfLB ,这是我的组件http : //pastebin.com/r1QYdNJx
以及这里我想如何使用注入功能 ,但是它不起作用: http : //pastebin.com/cs0V5wfq

我可以以某种方式注入对象,或者如何将args传递给注入的对象?

如果您在此类中没有任何其他依赖关系,那么也许它并不是您活动的真正依赖关系 ,您可以使用new 但是要回答您的问题,您希望为您的活动(或此类活动)提供一个子组件,并带有以下模块:

@Module
public class TestModule {
  private final String arg1;
  private final int arg2;
  private final boolean arg3;

  public TestModule(String arg1, int arg2, boolean arg3) {
    this.arg1 = arg1;
    this.arg2 = arg2;
    this.arg3 = arg3;
  }

  @Provides DaggerTestClass provideDaggerTestClass() {
    return new DaggerTestClass(arg1, arg2, arg3);
  }
}

并且您会像这样使用它:

IndexApplication.getApplication().getAppComponent()
    .daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))
    .inject(this);

如果您在此类中还具有其他依赖项,那么您可能希望实际使用工厂(可能是使用AutoFactory为您生成的),然后“手动注入”创建的对象:

private DaggerTestClass daggerTestClass; // note: no @Inject here

// …

// Inject other dependencies into the activity
IndexApplication.getApplication().getAppComponent().inject(this);
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
    .daggerTestFactory().create("arg1", 2, true);

暂无
暂无

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

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