java - Dagger 2 Activity 注入(inject)不起作用

标签 java android dependency-injection dagger-2

我正在尝试新的 Dagger 2,这是我第一次实现它,但我无法让它工作。我想我明白了这个概念并且我理解了这个例子 here

我尝试复制相同的结构,只是为我的示例稍作修改。

这是在我定义我想要的类的地方扩展图形的 AppComponent。

@ApplicationScope
@Component(modules = {AppModule.class, DataModule.class})
public interface EFAppComponent extends EFGraph {

    /**
     * An initializer that creates the graph from an application.
     */
    public final static class Initializer {

        private Initializer() {
        } // No instances.

        public static EFAppComponent init(EFApp app) {
            return Dagger_EFAppComponent.builder()
                    .appModule(new AppModule(app))
                    .build();
        }
    }
}


public interface EFGraph {

    public void inject(EFApp app);

    public ImageLoader imageLoader();

    public EventBus eventBus();

}

然后在每个模块中我提供相应的类。从这里一切正常,Dagger 接缝正确构建 Dagger_EFAppComponent。

然后在应用程序类中我使用构造函数初始化

component = EFAppComponent.Initializer.init(this);
component.inject(this);

然后我的目标是在我的 Activity 中注入(inject) ImageLoader 和 EventBus。为此,我创建了一个 ActivityComponent。

@ActivityScope
@Component(
        dependencies = EFAppComponent.class,
        modules = ActivityModule.class
)
public interface ActivityComponent {

    public void inject(BaseActivity activity);

}

然后从我的 Activity 中调用 inject。

activityComponent = Dagger_ActivityComponent.builder()
                .eFAppComponent(component)
                .activityModule(new ActivityModule(this))
                .build();
activityComponent.inject(this);

所以因为我在我的 Activity 中声明了@Inject EventBus eventBus 在应该注入(inject)注入(inject)方法调用之后。好吧,它不是。

因此,在逐步调试和跟踪我的应用程序和示例之后,我意识到 Dagger_ActivityComponent 构建不正确。

private final ActivityModule activityModule;
    private final EFAppComponent eFAppComponent;

    private Dagger_ActivityComponent(Builder builder) {  
        assert builder != null;
        this.activityModule = builder.activityModule;
        this.eFAppComponent = builder.eFAppComponent;
        initialize();
  }

如果初始化方法为空且没有 Provider 被声明为变量。

我错过了什么吗?我一整天都在努力让它发挥作用,但我没有成功。

感谢您的帮助。

最佳答案

好吧...在花了一整天时间后,我决定发布它,5 分钟后我找到了解决方案。

我正在为我的所有 Activity 使用 BaseActivity,我想我可以用它来注入(inject)我的组件,但接缝这是不可能的。

所以我只是在我的 ActivityComponent 中更改这一行

public void inject(BaseActivity activity) 

public void inject(MainActivity activity) 

所以我要注入(inject)依赖项的 Activity 的名称...

是什么让我想到了一个新问题。我怎样才能实现一个基本组件来处理我的所有 Activity ?或者我必须为我想要 DI 的每个 View /Activity/fragment 创建一个组件?

关于java - Dagger 2 Activity 注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29367921/

相关文章:

android - React Native Android 调试 APK 已安装,但未签名未安装

Android KitKat 不支持 TLSv1.2

c# - Unity Container RegisterType<TFrom, TTo> 问题

java - Zuul将相同的请求代理到另一个端口

java - 图像未出现在 netbeans 的 jsp 中

java - 从字符串中查找子字符串

Android 快速操作 UI 模式

jakarta-ee - TomEE 是如何实现依赖注入(inject)的?

java - Guice 代理支持循环依赖

java - 正在开发类似于 Android 的 BlackBerry 应用程序吗?