gpt4 book ai didi

android - 如何声明依赖

转载 作者:搜寻专家 更新时间:2023-11-01 07:46:11 25 4
gpt4 key购买 nike

我正在研究 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),在创建对象后调用方法)


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

// in a module

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

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


以下将用于在您无权访问或不想使用构造函数的地方注入(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com