ApplicationComponent.java
@Component(modules = SomeModule.class)
@ApplicationScope
public interface ApplicationComponent {
// stuff
ActivityComponent activityComponent();
}
ActivityComponent.java
@Subcomponent(modules = AnotherModule.class)
@ActivityScope
public interface ActivityComponent {
// stuff
void inject(MainActivity mainActivity);
}
SomeModule
可以使用 this 之类的内容进行覆盖。但是AnotherModule
怎么样?
一种解决方案是将这两个组件分开,但是如果我想重用父组件中的一些绑定(bind)该怎么办?
编辑:
MainActivity.java
onCreate(Bundle bundle) {
getApplicationComponent().getActivityComponent().inject(this);
}
编辑2:
ActivityRyle.java
init() {
application.setComponent(DaggerApplicationComponent.builder()
.someModule(new TestSomeModule(application))
.build();
}
edit3:我试图避免在Application
(创建主要组件的地方)中连接太多东西。
最佳答案
您也只需覆盖该模块即可。
请记住您创建子组件的方式:
public interface ApplicationComponent {
ActivityComponent activityComponent(/*needed modules go here*/);
}
因此,除非模块有无参数构造函数,否则必须将它们作为参数放在方法声明中。
如果您希望能够使用无参数构造函数覆盖模块,则必须将它们添加到方法签名中:
public interface ApplicationComponent {
ActivityComponent activityComponent(AnotherModule module);
}
在您的测试中,您只需提供您的子类。
关于android - Dagger2 子组件模块覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37489856/