android - 是否需要手动注入每个类?
问题描述
我正在尝试将 Dagger2 合并到我的应用程序中,但我尝试注入的对象始终是null
除非我手动调用inject()
. 我认为inject()
只有系统创建的活动/服务/片段才有必要。是否真的需要手动注入所有具有依赖关系的类?
这是我的简单示例:
public class Foo {
@Inject Bar bar;
...
}
我有一个模块要提供Bar
:
@Module
public final class BarModule {
public BarModule() {}
@Provides
Bar provideBar () {
return new Bar();
}
}
然后我有一个核心组件:
@Singleton
@Component(modules = {BarModule.class})
public interface AppComponent {
Bar buildBar();
void inject(Foo foo);
}
在我的应用程序中,我构建了组件:
DaggerAppComponent.builder().barModule(new BarModule()).build();
但是,bar
总是null
,除非我也打电话inject()
:
Foo foo = new Foo();
DaggerAppComponent.builder().barModule(new BarModule()).build().inject(foo);
真的有必要为每个具有依赖关系的类定义/调用注入吗?我在示例代码中的任何地方都没有看到这样的 inject() 调用,所以我认为我做的事情根本上是错误的。
编辑
根据@DavidMedenjak 的回答,我尝试了:
public class Bar {
@Inject
Bar() {}
public int hello(int b) {
return b + 5;
}
}
没有模块或组件,我现在做:
Log.i(TAG, "Hello is " + bar.hello(5));
它返回一个 NPE,因为 bar 为空。
编辑 2 我认为问题在于我没有通过创建组件并调用它来引导注入。我需要的是:
AppComponent comp;
comp = DaggerAppComponent.create();
bar = comp.buildBar();
这对于单级对象来说是没有意义的,但是对于依赖链,组件将创建链中的其余对象。
解决方案
我认为
inject()
只有系统创建的活动/服务/片段才有必要。
正确的。
是否真的需要手动注入所有具有依赖关系的类?
没有。您应该尽可能使用构造函数注入。
- 摆脱
BarModule
. 避免从带@Provides
注释的方法调用构造函数),您不需要模块来使用构造函数注入 添加
@Inject
到Bar
的构造函数以指示 Dagger 如何创建对象class Bar { @Inject Bar() {} }
这里的所有都是它的。Dagger 现在知道如何创建Bar
. 将作用域和限定符添加到类,依赖项作为构造函数参数。