android - Dagger 2 : How to use @Provides and @Binds in same module

标签 android dagger-2

我正在使用新的 Dagger2(2.11 版),并且正在使用新功能,例如 AndroidInjectorContributesAndroidInjector。我有一个 Activity 子组件,

        @Module
        abstract class ActivityBuilderModule {
            @ContributesAndroidInjector(modules = 
                   {UserListModule.class, MainFragmentModule.class})
            @ActivityScope
            abstract MainActivity bindsMainActivity();

        }



  @Module
  public abstract class MainFragmentModule {
    @ContributesAndroidInjector
    @FragmentScope
    @FragmentKey(UserListFragment.class)
    abstract UserListFragment bindsUserListFragment();

}

UserListModule 为 fragment 提供依赖项。一些依赖项我只想绑定(bind)实例,然后返回,比如

 @Binds
 @ActivityScope
 abstract UserListView mUserListView(UserListFragment userListFragment);

而不是简单地返回依赖,比如

@Provides
@ActivityScope
UserListView mUserListView(UserListFragment userListFragment){
    return userListFragment;
}

我的模块也包含一些@Provides 方法。我们可以在同一模块中同时使用 @Binds@Provides 方法吗?我尝试如下所示

        @Module
        public abstract class UserListModule {
            @Provides
            @ActivityScope
            UserListFragment mUserListFragment() {
                return new UserListFragment();
            }

            @Binds
            @ActivityScope
            abstract UserListView mUserListView(UserListFragment userListFragment);

           // other provides and binds methods...
           ......
           .....

        }

它是抛出错误

Error:(22, 8) 错误:dagger.internal.codegen.ComponentProcessor 无法处理此接口(interface),因为它的所有依赖项都无法解析。检查编译错误或生成代码的循环依赖。

有什么办法吗?

最佳答案

@Binds@ContributesAndroidInjector方法必须是抽象的,因为它们没有方法体。这意味着它们必须在接口(interface)或抽象类上进行。 @Provides方法可能是 static ,这意味着它们可以继续抽象类和 Java-8 编译接口(interface),但非静态(“实例”)@Provides方法不适用于抽象类。这在 Dagger 常见问题解答中明确列出,在 "Why can’t @Binds and instance @Provides methods go in the same module?" 部分下和 "What do I do instead?" .

如果您的 @Provides方法不使用实例状态,可以标记为static ,它可以进入与您的 @Binds 相邻的抽象类方法。如果没有,请考虑将绑定(bind)设置为 @Binds@ContributesAndroidInjector进入一个单独的类——可能是一个静态嵌套类——并使用 includes 包括它Dagger 的属性 @Module注释。

关于android - Dagger 2 : How to use @Provides and @Binds in same module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618763/

相关文章:

java - 在 Android 模块化项目中使用 Dagger 2.11

android - Dagger 2 : error: [ComponentProcessor:MiscError] circular dependency with generated code

安卓测试 : use Dagger2 + Gradle

java - OpenCV 错误 : Bad argument (The array of layer neuron counters must be an integer vector)

android - 即使应用程序被杀死后,Dagger AppComponent 仍然可用

android - 如何在 Room 数据库中存储来自 url 的图像 (Java)

android - 我的蓝牙连接只读取零

android - Dagger2 的项目结构

android - 如何摆脱 ListView 布局中的黑行

java - 当 URL 相似时,Android WebView canGoBack() 返回 false