android - 非活动类中的 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 的随机类中不可用。那么让匕首初始化我的领域的正确方法是什么?
解决方案
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
推荐阅读
- python - 线程中的Python套接字recv
- python - 如何验证python函数中行代码的输出
- javascript - 使用引导程序 4 选项卡时将活动类存储在本地存储中
- c++ - 创建将一些文本放入 QTextEdit 的插槽时出现问题
- vba - 将字符串格式的月份转换为 Word 宏中的数字
- java - Gson 使用 TypeAdapter 或 Json Deserializer 将数据从错误列表转换为空列表
- scala - 优先级队列中的不同元素
- windows - 自动热键脚本速度和防止垃圾邮件点击
- python - 在 Raspberry Pi 上使用 Telegram 接收并打印一条消息以损坏 USB 打印机
- kotlin - 如何设计具有无限阻塞循环的工人垂直?