如何声明依赖

How to declare dependencies

我正在研究 Dagger 2,所以我想了解一些基本的东西。我有以下代码:

@Module
public class MainModule {

@Provides
public Presenter provideMainActivityPresenter(Model model){
    return new MainPresenter(model);

}

@Provides
public Model provideMainModel(){
    return new MainModel();
 }
}

我的 MainPresenter class 看起来像这样:

public class MainPresenter implements Presenter {

@Nullable
private ViewImpl view;
private Model model;



public MainPresenter(Model model) {
    this.model = model;
}

@Override
public void setView(ViewImpl view) {
    this.view = view;
  }
 }

除了上面的代码,我可以执行以下操作吗?

public class MainPresenter implements Presenter {

@Nullable
private ViewImpl view;

@Inject
Model model;


@Override
public void setView(ViewImpl view) {
    this.view = view;
 }
}

因为 MainPresenter 依赖于 Model 而不是 @Nullable
或者这是错误的?

我不明白什么时候应该将依赖项作为构造函数参数,或者什么时候应该使用 @Inject

你基本上有 3 种使用 Dagger 的方法

  • 构造函数注入
  • 字段注入
  • 自己从模块中提供

(还有方法注入,在创建对象后调用方法)


以下是使用提供您的 class 的模块。虽然没有错,但这是编写和维护的最大开销。您通过传入请求的依赖项和 return 它来创建对象:

// in a module

@Provides
public Presenter provideMainActivityPresenter(Model model){
  // you request model and pass it to the constructor yourself
  return new MainPresenter(model);
}

这应该与需要额外设置的东西一起使用,例如 GsonOkHttpRetrofit,这样您就可以在一个地方创建具有所需依赖项的对象。


以下将用于在您无权访问或不想使用构造函数的地方注入对象。您注释该字段并在组件中注册一个方法以注入您的对象:

@Component class SomeComponent {
  void injectPresenter(MainPresenter presenter);
}

public class MainPresenter implements Presenter {

  // it's not annotated by @Inject, so it will be ignored
  @Nullable
  private ViewImpl view; 

  // will be field injected by calling Component.injectPresenter(presenter)
  @Inject
  Model model;

  // other methods, etc
}

这还将为您提供在演示者处注册所有 classes 的开销,并且应该在您不能使用构造函数(如活动、片段或服务)时使用。这就是为什么所有这些 Dagger 示例都使用那些 onCreate() { DaggerComponent.inject(this); } 方法来注入 Android 框架的部分内容。


最重要的是你可以使用构造函数注入。你用 @Inject 注释构造函数,让 Dagger 找出如何创建它。

public class MainPresenter implements Presenter {

  // not assigned by constructor
  @Nullable
  private ViewImpl view;

  // assigned in the constructor which gets called by dagger and the dependency is passed in
  private Model model;

  // dagger will call the constructor and pass in the Model
  @Inject 
  public MainPresenter(Model model) {
    this.model = model;
  }
}

这只需要您注释 class 构造函数,Dagger 将知道如何处理它,前提是可以提供所有依赖项(构造函数参数,本例中的模型)。


上面提到的所有方法都会创建一个对象,可以/应该在不同的情况下使用。

所有这些方法要么将依赖项传递给构造函数,要么直接注入 @Inject 带注释的字段。因此,依赖项应该在构造函数中或由 @Inject 注释,以便 Dagger 知道它们。

我还写了一篇关于 the basic usage of Dagger 2 的博客 post,其中包含一些更详细的信息。