【发布时间】:2018-06-27 11:58:49
【问题描述】:
我有 2 个类,我希望对其进行依赖注入。基本上两者都需要彼此的对象来执行某些任务。
头等舱
public class AppMobilePresenter {
AppPresenter appPresenter;
@Inject
public AppMobilePresenter(AppPresenter appPresenter) {
this.appPresenter = appCMSPresenter;
}
}
它的模块
@Module
public class AppMobilePresenterModule {
@Provides
@Singleton
public AppMobilePresenter providesAppMobilePresenter(AppPresenter appPresenter) {
return new AppMobilePresenter(appPresenter);
}
}
二等
public class AppPresenter {
AppMobilePresenter appMobilePresenter;
@Inject
public AppPresenter() {
}
@Inject
void setAppMobilePresenter(AppMobilePresenter appMobilePresenter){
this.appMobilePresenter=appMobilePresenter;
}
}
它的模块
@Module(includes = { AppMobilePresenterModule.class})
public class AppPresenterModule {
@Provides
@Singleton
public AppPresenter providesAppPresenter() {
return new AppPresenter();
}
}
我对两者都有一个共同的组件
@Singleton
@Component(modules = {AppPresenterModule.class})
public interface AppPresenterComponent {
AppPresenter appPresenter();
}
从我的应用程序类构建组件并运行应用程序后,我在 AppPresenter 类中获得了 AppMobilePresenter 对象 null。 方法注入是否还需要做其他事情。
【问题讨论】:
-
我不认为,这种循环依赖是一个很好的解决方案。可能制作一个通用 Module ,这对于这两个类的初始化都是必需的。首先在 Application 类中创建该依赖项。为这两个提供相同的内容。
-
@Sreehari 我知道这不是一个好的解决方案,但根据我当前的代码库,这是我能得到的唯一解决方案。我必须在课堂上拥有彼此的对象。
标签: android dependency-injection dagger-2