没有 @Provides-annotated 方法就不能提供上下文,但它是吗?

Context cannot be provided without an @Provides-annotated method, but it is?

我有以下简单模块:

@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();

它在编译时抛出这个错误:Error:(22, 13) error: android.content.Context cannot be provided without an @Provides-annotated method,但正如你所看到的,它被注释为 @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();

}