android – 如果没有@ Provide-annotated方法,则无法提供上下文,但它是?

我有以下简单的模块:
@Module
public class ApplicationModule {

    private CustomApplication customApplication;

    public ApplicationModule(CustomApplication customApplication) {
        this.customApplication = customApplication;
    }

    @Provides @Singleton CustomApplication provideCustomApplication() {
        return this.customApplication;
    }

    @Provides @Singleton @ForApplication Context provideApplicationContext() {
        return this.customApplication;
    }

}

和相应的简单组件:

@Singleton
@Component(
        modules = ApplicationModule.class
)
public interface ApplicationComponent {

    CustomApplication getCustomApplication();

    Context getApplicationContext();

}

我在这里创建组件:

public class CustomApplication extends Application {

    ...

    private ApplicationComponent component;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();

它会在编译时抛出此错误:错误:(22,13)错误:如果没有@ Provide-annotated方法,则无法提供android.content.Context,但是您可以看到它使用@Provides进行注释.

这真的很奇怪,因为当我将限定符注释关闭时,问题消失了.

以防万一,这是我的@ForApplication限定词:

@Qualifier @Retention(RUNTIME)
public @interface ForApplication {
}

这实际上是一本教材Dagger2的例子.我究竟做错了什么?

解决方法

经过一段时间的尝试和错误,我似乎发现了原因,这是Context的含糊之处,因为在需要Context的某些地方,缺少@ForApplication.

此外,这可能是我对Dagger2的虚弱的理解,但是这个样板很容易出现开发者的错误.

无论如何…对于发现问题的任何人,您只需要在使用依赖关系的每个地方添加限定符注释:

@Singleton
@Component(
        modules = ApplicationModule.class
)
public interface ApplicationComponent {

    CustomApplication getCustomApplication();

    @ForApplication Context getApplicationContext();

}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...