没有@Annex-annotated方法就无法提供上下文,但它是?

Edu*_*eda 13 android dagger dagger-2

我有以下简单的模块:

@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;
    }

}
Run Code Online (Sandbox Code Playgroud)

以及各自的简单组件:

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

    CustomApplication getCustomApplication();

    Context getApplicationContext();

}
Run Code Online (Sandbox Code Playgroud)

我在这里创建组件:

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();
Run Code Online (Sandbox Code Playgroud)

它会在编译时抛出此错误:Error:(22, 13) error: android.content.Context cannot be provided without an @Provides-annotated method但是正如您所看到的那样,它会被注释掉@Provides.

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

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

@Qualifier @Retention(RUNTIME)
public @interface ForApplication {
}
Run Code Online (Sandbox Code Playgroud)

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

Edu*_*eda 24

经过一段时间的反复试验,我似乎找到了原因,这是Context因为@ForApplication在一些Context需要的地方缺少了因为模糊.

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

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

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

    CustomApplication getCustomApplication();

    @ForApplication Context getApplicationContext();

}
Run Code Online (Sandbox Code Playgroud)