如何声明依赖项

时间:2017-05-06 12:20:27

标签: android dependency-injection dagger-2

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

@Module
public class MainModule {

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

}

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

我的MainPresenter课程如下:

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

1 个答案:

答案 0 :(得分:4)

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

  • 构造函数注入
  • 现场注射
  • 自己从模块中提供

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

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

// 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
}

这也将为您提供在演示者处注册所有课程的开销,并且应该在您不能使用构造函数(如“活动”,“片段”或“服务”)时使用。这就是为什么所有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;
  }
}

这只需要你注释你的类构造函数,Dagger将知道如何处理它,因为可以提供所有依赖项(构造函数参数,本例中的Model)。

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

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

我还撰写了一篇关于the basic usage of Dagger 2的博客文章,其中包含更多细节。