我正在学习dagger2
依赖注入框架。我喜欢它如何注入依赖性。我读了这篇文章 https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 我看到他们在两个Modules
的帮助下解释了这一点.
AppModule
和NetModule
是两个Modules
。两者都有构造函数,所以它们像这样实例化我们的依赖关系图的一个实例
mNetComponent = DaggerNetComponent.builder()
// list of modules that are part of this component need to be created here too
.appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
.netModule(new NetModule("https://api.github.com"))
.build();
假设我还有一个没有构造函数的Modules
,那么我将如何初始化它,因为其他 2 个模块需要构造函数中的值?
谢谢
如果你的第三个模块不需要构造函数,Dagger2会自动将其添加到组件中,如果你把它列在@Component
的modules
中,就像这样
@Component(modules = {
AppModule.class,
NetModule.class,
ThirdModule.class // module without constructor
})
public interface NetComponent{
// ...
}
假设你的第三个模块是 TestModule:
您可以简单地执行此操作:
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://api.github.com"))
.testModule(new TestModule())
.build();
注意:这里 .testModule 会给你弃用的警告,这意味着你甚至不必定义没有构造函数的模块。它们被隐式添加到图形中。