如何在Dagger2中实例化我们的依赖图的实例

时间:2017-03-31 18:59:10

标签: java android dagger-2

我正在学习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个模块需要构造函数中的值?

由于

2 个答案:

答案 0 :(得分:2)

如果你的第三个模块不需要构造函数,那么如果你在@Component modules中列出它,Dagger2会自动将它添加到组件中:

 @Component(modules = {
     AppModule.class,
     NetModule.class,
     ThirdModule.class // module without constructor
 })
 public interface NetComponent{
     // ...
 }

答案 1 :(得分:0)

让我们说你的第三个模块是TestModule:

你可以这样做:

 mNetComponent = DaggerNetComponent.builder()        
                .appModule(new AppModule(this)) 
                .netModule(new NetModule("https://api.github.com"))
                .testModule(new TestModule())
                .build();

注意:这里.testModule会给你不赞成的警告,这意味着你甚至不必定义没有构造函数的模块。它们被隐式添加到图表中。