我有以下简单模块:
@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的例子。我做错了什么?
答案 0 :(得分:24)
经过一段时间的反复试验后,我似乎找到了原因,这是Context
的歧义,因为在需要@ForApplication
的某些地方缺少Context
。< / p>
此刻可能是我对Dagger2的脆弱理解,但这个样板很容易出现开发人员错误。
无论如何......对于发现问题的任何人,您只需在每个使用依赖项的地方添加限定符注释:
@Singleton
@Component(
modules = ApplicationModule.class
)
public interface ApplicationComponent {
CustomApplication getCustomApplication();
@ForApplication Context getApplicationContext();
}