您基本上有 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);
}
这应该与需要额外设置的东西一起使用,例如Gson
, OkHttp
, or Retrofit
这样您就可以在一个地方创建具有所需依赖项的对象。
以下内容将用于在您无权访问或不想使用构造函数的情况下注入对象。您注释该字段并在组件上注册一个方法来注入您的对象:
@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 将知道如何处理它,前提是可以提供所有依赖项(构造函数参数,本例中的模型)。
上面提到的所有方法都会创建一个对象,并且可以/应该在不同的情况下使用。
所有这些方法要么将依赖项传递给构造函数,要么注入@Inject
直接注释字段。因此,依赖关系应该位于构造函数中或由@Inject
这样 Dagger 就知道他们了。
我还写了一篇关于Dagger 2 的基本使用 http://blog.davidmedenjak.com/android/2016/05/04/dagger-2-introduction.html以及一些进一步的细节。