java - Dagger2 将应用程序拆分为多个 gradle 模块

标签 java android dagger-2

我有以下 Dagger 组件结构:

@Singleton @Component(modules = CoreModule.class)
public interface CoreComponent{
    ComponentA plus(ModuleA module);

    ComponentB plus(ModuleB module);
}

@ActivityScope @Subcomponent(modules = ModuleA.class)
public interface ComponentA {
    ComponentA inject(FragmentA fragment);
}

@ActivityScope @Subcomponent(modules = ModuleB.class)
public interface ComponentA {
    ComponentB inject(FragmentB fragment);
}

客户端代码如下所示:

class FragmentA extends Fragment{
    public FragmentA(){
        App.getCoreComponent().plus(new ModuleA()).inject(this);
    }
}

我决定将应用程序拆分为几个 gradle 模块。 我想要 gradle Core 模块和 2 个模块 A 和 B 依赖于核心但彼此不了解。

我的问题是 CoreComponent 使用来自 AB 的导入来创建子组件。因此,Core 依赖于 AB

我试图使用@Components.Builder来解决它,但这也需要在根组件中包含 dagger 模块以及一组所有子组件。

有什么方法可以消除根组件对其子组件的依赖。

通过根组件的依赖,我的意思是它应该知道使用它的所有子组件。

根据 Dagger 文档:

Subcomponents are components that inherit and extend the object graph of a parent component. You can use them to partition your application’s object graph into subgraphs either to encapsulate different parts of your application from each other or to use more than one scope within a component.

An object bound in a subcomponent can depend on any object that is bound in its parent component or any ancestor component, in addition to objects that are bound in its own modules. On the other hand, objects bound in parent components can’t depend on those bound in subcomponents; nor can objects bound in one subcomponent depend on objects bound in sibling subcomponents.

最佳答案

您将无法使用子组件删除依赖项CoreComponent -> ComponentA, ComponentB。这不是子组件的工作方式。

您可以尝试通过使 ComponentAComponentB 依赖于 CoreComponent (ComponentA, ComponentB -> CoreComponent)。这将要求您显式导出 CoreComponent 中的对象。

作为旁注,我必须警告您,您正在尝试做的事情可能会在未来引起大麻烦:通过第三方框架耦合模块的内部实现很少是一个好主意。

关于java - Dagger2 将应用程序拆分为多个 gradle 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206637/

相关文章:

android - 如何在 AndroidManifest.xml 中指定超过 1 个自定义应用程序作为我的应用程序?

android - eclipse 不显示 Avd 管理器窗口和 android 项目

android - 如何使用 Dagger2 将 Activity 范围内的依赖项替换为模拟

java - & 位运算符如何在这里工作?

android - Sqlite 数据库生命周期?应用程序关闭时它会被删除吗?

android - 使用 Dagger 2 提供函数依赖

AndroidInjector<android.app.Activity> 不能在没有 @Provides- 或 @Produces- 注释的方法的情况下提供

java - 分割后打印一个值(java)

java - JFace : Clear contents of a ListViewer prior to setting input.(不使用Selection监听器清除所有内容)

java - 如何在 Spring Boot 测试中禁用 `@EnableKafka`?