我有以下简单的模块:
@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();
}