13

我有以下简单的模块:

@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 示例。我究竟做错了什么?

4

1 回答 1

24

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

也可能是我目前对 Dagger2 的脆弱理解,但这个样板很容易出现开发人员错误。

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

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

    CustomApplication getCustomApplication();

    @ForApplication Context getApplicationContext();

}
于 2015-05-31T00:53:10.637 回答