首页 > 解决方案 > 非活动类中的 Dagger 2 依赖项

问题描述

因此,有很多教程展示了如何使用 Dagger 2 将依赖项注入到活动类中。但由于某种原因,依赖项似乎从未被插入到不是活动/片段/服务的类中。我想知道如何将依赖项插入到普通类中。

现在,我正在尝试将匕首注入一个字段,但该字段仍然为空。我假设错误是我没有告诉匕首进行注射。但我不确定如何解决这个问题。

@Module
public class TestModule {
    @Provides 
    @Singleton
    String provideTestString() {
        return "test string";
    }
}
@Singleton
@Component(modules = { TestModule.class })
public interface TestComponent {
    void inject(TestClass testClass);
    String getTestString();
}
class TestClass {
    @Inject
    String testString;

    public boolean isTestStringNull() {
        return testString == null;
    }
}
Log.d("---", "is test string null: " + new TestClass().isTestStringNull());//is true

虽然我可以在 Application 的子类中调用 DaggerTestComponent.create(),但它在不了解 Application 的随机类中不可用。那么让匕首初始化我的领域的正确方法是什么?

标签: androiddagger-2

解决方案


class TestClass {
    @Inject
    String testString;

    @Inject
    TestClass() {}
}

@Singleton
@Component(modules = { TestModule.class })
public interface TestComponent {
    TestClass testClass();

    String testString();
}

Log.d("---", "is test string null: " + component.testClass().isTestStringNull());//is false

推荐阅读