本文介绍了没有@Provides注释的方法就无法提供上下文,但是它是吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单模块:

@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)错误:如果没有@Provides批注的方法,就无法提供android.content.Context,但是您可以看到它用 @Provides 批注。

It throws this error at compile time: Error:(22, 13) error: android.content.Context cannot be provided without an @Provides-annotated method, but as you can see it is annotated with @Provides.

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

It's really strange because the problem goes away when I take the qualifier annotation off.

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

Just in case, this is my @ForApplication qualifier:

@Qualifier @Retention(RUNTIME)
public @interface ForApplication {
}

这实际上是一本教科书Dagger2例。我在做什么错?

This is practically a textbook Dagger2 example. What am I doing wrong?

推荐答案

经过一段时间的反复试验,我似乎已经找到了原因, 上下文的歧义,因为在某些上下文 @ForApplication c)是必需的。

After quite a while of trial and error I've seem to found the cause, it's the ambiguity of Context because @ForApplication is missing in some places where Context is needed.

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

Also it may be my frail understanding of Dagger2 at the moment, but this boilerplate is quite prone to developer errors.

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

Anyhow... for anyone that finds the problem you just have to add the qualifier annotations in every place that dependency is used:

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

    CustomApplication getCustomApplication();

    @ForApplication Context getApplicationContext();

}

这篇关于没有@Provides注释的方法就无法提供上下文,但是它是吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 19:16