我正在研究 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
最佳答案
你基本上有 3 种使用 Dagger 的方法
- 构造函数注入(inject)
- 字段注入(inject)
- 自己从模块中提供
(还有方法注入(inject),在创建对象后调用方法)
以下是使用提供您的类的模块。虽然没有错,但这是编写和维护的最大开销。您可以通过传入请求的依赖项来创建对象并返回它:
// 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
或Retrofit
,以便您可以在具有所需依赖项的一处。
以下内容将用于在您无权访问或不想使用构造函数的情况下注入(inject)对象。您注释该字段并在组件中注册一个方法来注入(inject)您的对象:
@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
}
这还将为您提供在演示者处注册所有类的开销,并且应该在您无法使用构造函数(例如 Activity 、 fragment 或服务)时使用。这就是为什么所有这些 Dagger 示例都有这些 onCreate() { DaggerComponent.inject(this); }
方法来注入(inject) Android 框架的各个部分。
最重要的是,您可以使用构造函数注入(inject)。您使用 @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
带注释的字段。因此,依赖关系应该位于构造函数中或由 @Inject
注释,以便 Dagger 了解它们。
我还写了一篇关于 the basic usage of Dagger 2 的博文还有一些进一步的细节。
关于android - 如何声明依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820382/