java - 错误 : [Dagger/MissingBinding] when trying building the project

标签 java android dependency-injection dagger-2 dagger

我有一个服务类,我想通过 Dagger 提供它。但是我在下面收到此错误:

error: [Dagger/MissingBinding] service.KeyStoreService cannot be provided without an @Inject constructor or an @Provides-annotated method. service.KeyStoreService is provided at di.component.ApplicationComponent.getKeyStoreService()

这是我的组件类:

@ApplicationScope
@Component(modules = {ApplicationContextModule.class, KeyStoreModule.class})
public interface ApplicationComponent {

    @ApplicationContext
    Context getApplicationContext();

    KeyStoreService getKeyStoreService();

}

这是我的 KeyStoreModule:

@Module(includes = {ApplicationContextModule.class})
public class KeyStoreModule {

    @Provides
    @ApplicationScope
    KeyStoreServiceInterface getKeyStoreService(@ApplicationScope Context context){
        File file = new File(context.getFilesDir(), "keystore/keystore");
        return new KeyStoreService(file);
    }
}

KeyStoreService 实现了 KeyStoreServiceInterface。

这是我启动 Dagger2 的方式:

public class MyApplication extends Application {

    private ApplicationComponent applicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        applicationComponent = DaggerApplicationComponent.builder()
                .applicationContextModule(new ApplicationContextModule(this))
                .build();

    }

}

有人知道它可能哪里出错了吗?我在 Stackoverflow 上查看了类似的问题,但没有找到任何对我有帮助的问题。

最佳答案

有一件事:Dagger 提供基于特定类型 的实例。这里有几种方法可以解决这个问题

  • KeyStoreModule中将getKeyStoreService方法的返回类型从KeyStoreServiceInterface修改为KeyStoreService
  • ApplicationComponentgetKeyStoreService方法的返回类型从KeyStoreService改为KeyStoreServiceInterface
  • 创建一个带有 @Binds 注释的抽象方法,它将接收 KeyStoreService 并且返回类型将是 KeyStoreServiceInterface(为了做到这一点整个模块应该是抽象的 - 因此可以使用 @Binds 注释创建单独的抽象模块,或者使 KeyStoreModule 抽象并修改 getKeyStoreService 方法是静态的)
  • 同样,使用 @Binds 注释将 KeyStoreService 实例映射到提供的 KeyStoreServiceInterface,但应用 @InjectKeyStoreService 构造函数上注释并通过 Dagger 提供 keystore File
  • 不使用@Binds注解,而是在KeyStoreService构造函数上应用@Inject注解,并通过File提供 keystore Dagger

关于java - 错误 : [Dagger/MissingBinding] when trying building the project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402053/

相关文章:

java - Dagger2 Named(@Named) 多态或不同对象注入(inject)

java - 为什么此音频文件可在Windows中工作,而在Ubuntu中却不能工作?

java - Json 和多个用户定义的对象错误

java - 数据截断: Data too long for column 'Phone' at row 1

javascript - 与桌面浏览器相比,移动浏览器有多强大?

android - 尝试在 Cocos2d-X C++ 中设置一个带有整数的 CCLabelTTF 作为其字符串的一部分

java - 如何在 Android 中将 ArrayLIst 项转换为 json 对象

java - Pane 未调整到其转换后的尺寸

java - Guice:将依赖项注入(inject)@provides提供者

c# - 通过工厂创建实例时隔离实例的依赖关系(以及该实例的依赖关系)