java - 如何使用 Dagger2 在其构造函数中注入(inject)带有参数的对象

标签 java dependency-injection dagger-2

更新

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

类(class) http://pastebin.com/srhu4eB7

这是注入(inject) http://pastebin.com/wLbxBQqb

我正在学习如何在我的项目中使用 dagger2,但我不知道如何注入(inject)这个依赖项。 我有一个带有构造函数的测试类,我必须传递 3 个参数,这些参数来 self 想要注入(inject)我的类的 Activity 。 这是我的测试类:http://pastebin.com/XqRNFbvj 这是我的测试类的模块:http://pastebin.com/r4wmqfLB这是我的组件:http://pastebin.com/r1QYdNJx
这里我想如何使用注入(inject),但它不起作用:http://pastebin.com/cs0V5wfq

我可以以某种方式注入(inject)这样的对象吗?或者如何将参数传递给注入(inject)的对象?

最佳答案

如果您在此类中没有任何其他依赖项,那么它可能并不是您的 Activity 的真正依赖项,您可以只使用 new。但要回答您的问题,您需要为您的 Activity (或此类 Activity )提供一个带有如下模块的子组件:

@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 为您生成),然后“手动注入(inject)”创建的对象:

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

关于java - 如何使用 Dagger2 在其构造函数中注入(inject)带有参数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39635620/

相关文章:

android - Dagger 2 : Inject child class based on logic

android - 如何创建 ViewModel 并使用 dagger 2 向其注入(inject)存储库?

java - 在 Spring Security 中配置自定义对象

java - Android 上的黑屏 - Codenameone

java - 单击“确定”按钮时 GUI 登录系统没有反应

java - Java 主从中的套接字

c# - 如何将依赖项注入(inject) MVVM View Model 类?

c# - CommandHandler 装饰器依赖

kotlin - 为什么要为ApplicationContext对象添加注释@ApplicationContext?

android - 启动 Dagger2,如何构建结构?