2016-05-27 76 views
2

ApplicationComponent.javaDagger2子组件模块覆盖

@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怎么样?

一个解决方案是将这两个组件分开,但是如果我想重新使用父项的某些绑定呢?

编辑:

MainActivity.java

onCreate(Bundle bundle) { 
    getApplicationComponent().getActivityComponent().inject(this); 
} 

EDIT2:

ActivityRyle.java

init() { 
    application.setComponent(DaggerApplicationComponent.builder() 
        .someModule(new TestSomeModule(application)) 
        .build(); 
} 

EDIT3:我试图避免Application接线太多的东西(其中主组件被创建)。

+0

请始终包含与您的问题相关的所有内容,并且不要只链接到外部样本。 –

回答

0

你也只是重写模块。

请记住,你如何创建子:

public interface ApplicationComponent { 

    ActivityComponent activityComponent(/*needed modules go here*/); 
} 

所以,除非你有没有参数的构造为模块,你必须把它们作为方法声明中的参数。

如果您希望能够覆盖一个无参数的构造模块,你必须将它们添加到您的方法签名:

public interface ApplicationComponent { 

    ActivityComponent activityComponent(AnotherModule module); 
} 

并在您的测试,你只需提供你的子类。

+1

使用示例代码更新了如何使用ActivityComponent。在测试中,我将如何通过测试模块?对于ApplicationComponent,它可以在ActivityTestRule中完成,并将组件设置为当前的应用程序。但我无法找到一种方法来为子组件做这样的事情。 – mbmc

1

您需要将模块声明为子组件工厂方法的输入参数。

+0

我在哪里/如何通过测试模块? – mbmc

+0

不是'ActivityComponent activityComponent();'write'ActivityComponent activityComponent(AnotherModule anotherModule)' – EpicPandaForce

+0

是的,我得到那部分内容,但是从测试中,如何将测试模块分配给该组件,以便活动正在使用它?在主应用程序中添加一个'setActivityComponent'? – mbmc