匕首2法注射?

时间:2018-06-27 11:58:49

标签: android dependency-injection dagger-2

我有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。 方法注入还需要做其他事情吗?

1 个答案:

答案 0 :(得分:1)

在调用构造函数时,方法注入不会发生,就像在@Provides方法中一样;如果要进行方法注入,则Dagger需要在其生成的代码中调用@Inject注释的构造函数。

您似乎更喜欢构造函数注入,无论如何它还是比较安全的,但是为了避免依赖周期,正在尝试方法注入。不幸的是,这行不通。相反,请切换回构造函数注入和use the technique shown here

@Singleton
public class AppMobilePresenter {
  AppPresenter appPresenter;

  @Inject
  public AppMobilePresenter(AppPresenter appPresenter) {
    this.appPresenter = appCMSPresenter;
  }
}

@Singleton
public class AppPresenter {
  Provider<AppMobilePresenter> appMobilePresenterProvider;

  @Inject
  public AppPresenter(Provider<AppMobilePresenter> appMobilePresenterProvider) {
    this.appMobilePresenterProvider = appMobilePresenterProvider;
  }
}

上面的代码可以使用相同的组件,并且不需要任何模块。一个警告是要从AppPresenter转到AppMobilePresenter,您需要调用appMobilePresenterProvider.get(),您可以在除构造函数和@Inject方法之外的任何地方调用。这就解决了构造问题:否则Dagger必须先创建AppPresenter才能创建AppMobilePresenter,并且必须先创建AppMobilePresenter才能创建AppPresenter。不过,它可以创建一个Provider,并在以后调用它时提供实例。

如果将来的读者真的需要字段或方法注入,则可以在删除模块并切换到方法注入Provider<AppMobilePresenter>时,不理会@Inject构造函数和方法,这是必需的,因为方法注入具有相同的构造顺序依赖周期与构造函数注入有关。