我有一个服务类,我想通过 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
- 将
ApplicationComponent
中getKeyStoreService
方法的返回类型从KeyStoreService
改为KeyStoreServiceInterface
- 创建一个带有
@Binds
注释的抽象方法,它将接收KeyStoreService
并且返回类型将是KeyStoreServiceInterface
(为了做到这一点整个模块应该是抽象的 - 因此可以使用@Binds
注释创建单独的抽象模块,或者使KeyStoreModule
抽象并修改getKeyStoreService
方法是静态的) - 同样,使用
@Binds
注释将KeyStoreService
实例映射到提供的KeyStoreServiceInterface
,但应用@Inject
在KeyStoreService
构造函数上注释并通过 Dagger 提供 keystoreFile
- 不使用
@Binds
注解,而是在KeyStoreService
构造函数上应用@Inject
注解,并通过File
提供 keystore Dagger
关于java - 错误 : [Dagger/MissingBinding] when trying building the project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402053/