Android Dagger依赖注入在私有字段上失败 [英] Android Dagger Dependency Injection fails on private Fields
问题描述
我是dagger的新手(尽管我有使用Weld开发Java EE WebApp的DI经验).
I'm new to dagger (though I have experience with DI from working on Java EE WebApps using Weld).
我想要做的是将依赖项注入到类中.该字段是私有的.
What I'm trying to do is to inject a dependency into a class. The field is private.
然后Dagger抛出一个异常,说明它无法注入私有字段.
Dagger then throws an exception stating it can't inject into a private field.
这是什么原因?
毕竟,即使在android上,也可以使用反射写入私有字段.
After all it is possible to write to private fields using reflections, even on android..
如果我将字段的可见性设置为非私有,则注入似乎有效.
If I set the visibility of the field to something other than private the injection seems to work.
推荐答案
使私有字段包可见"可能并不总是您想要的. Dagger文档提出以下建议:
Making a private field 'package visible' may not always be what you want. The Dagger documentation suggests the following:
注入最终字段和私有成员.为了获得最佳性能 匕首生成代码.通过使用构造函数来解决此问题 注射.
Injecting final fields and private members. For best performance Dagger generates code. Work around this by using constructor injection.
这是一个例子:
private ItemFactoryImpl itemFactory;
private BuildingFactory buildingFactory;
@Inject
public World(ItemFactoryImpl itemFactory, BuildingFactory buildingFactory) {
this.itemFactory = itemFactory;
this.buildingFactory = buildingFactory;
}
这篇关于Android Dagger依赖注入在私有字段上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!