我正在使用Android Dagger2,但我收到以下错误。
我的模块课程:
@Module
public class ApplicationModule {
private final App mApp;
public ApplicationModule(App app) {
this.mApp = app;
}
@Provides
@Singleton
@ContextType("Application")
App provideApplicationContext(){
return mApp;
}
@Provides
@Singleton
P2PService provideP2PService(App context){
return new P2PService(context);
}
}
我的组件类:
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
@ContextType("Application")
App getContext();
P2PService p2pService();
}
符合,错误消息:
Error:(21, 16) error: com.sen5.smartlifebox.App cannot be provided without an @Inject constructor or from an @Provides-annotated method.
com.sen5.smartlifebox.App is injected at
com.sen5.smartlifebox.di.module.ApplicationModule.provideP2PService(context)
com.sen5.smartlifebox.data.p2p.P2PService is provided at
com.sen5.smartlifebox.di.component.ApplicationComponent.p2pService()
非常感谢任何建议!
答案 0 :(得分:1)
Dagger告诉您,它不知道如何在App
方法中提供provideP2PService
依赖关系。
您必须将@ContextType("Application")
添加到方法的参数中,如下所示:
@Provides
@Singleton
P2PService provideP2PService(@ContextType("Application") App context) {
return new P2PService(context);
}
答案 1 :(得分:1)
说实话,我对你的代码中的 @ContextType(" Application")感到困惑!
顺便说一句,对代码进行这些更改,它会起作用:
<强> ApplicationModule.java 强>:
port ip(count of same ip) service numberOfTimes
22 4 ssh 399 (#1+#5+#7+#9)
80 3 www 68 (#2+#6+#8)
<强> ApplicationComponent.java 强>:
@Module
public class ApplicationModule {
private final App mApp;
public ApplicationModule(App app) {
this.mApp = app;
}
@Provides
@Singleton
App provideApplicationContext(){
return mApp;
}
@Provides
@Singleton
P2PService provideP2PService(App context){
return new P2PService(context);
}
}
这就是你如何使用这种注射方式:
<强> App.java 强>:
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(MainActivity mainActivity);
}
<强> MainActivity.java 强>:
public class App extends Application {
ApplicationComponent applicationComponent;
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
@Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build();
}
}
有关更多参考资料,您可以查看此示例仓库,其中包含使用Dagger,MVP,RxJava和其他有用库开发的Android应用程序:
我希望它有所帮助:)