Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于dagger2的问题 #1

Open
bigggge opened this issue Sep 19, 2016 · 6 comments
Open

关于dagger2的问题 #1

bigggge opened this issue Sep 19, 2016 · 6 comments

Comments

@bigggge
Copy link

bigggge commented Sep 19, 2016

provideMainActivityPresenter(ApiService apiService)方法 可以用来注入presenter @Inject MainActivityPresenter presenter;

其中参数apiService是通过dependencies = AppComponent.class获取ApiServiceModule类里的provideApiService方法得到的。不知道这么理解对不对?

那么,provideApplication,provideMainActivity方法在你的代码中起什么作用呢?我没有找到使用这两个方法的地方,望解答,谢谢

@maoruibin
Copy link
Owner

@bigggge

@Module
public class AppModule {

    private Application application;

    public AppModule(Application application){
        this.application=application;
    }

    @Provides
    @Singleton
    public Application provideApplication(){
        return application;
    }
}

Module 是提供实例的地方,这里定义了一个 Application 类型的变量 application ,那么 这个 module就需要一个返回值为 Application 的方法用于提供给 Dagger 框架 ,最终这个方法会被 Dagger 调用到!这个方法名是随意的,但是返回值是一定的

@maoruibin
Copy link
Owner

其中参数apiService是通过dependencies = AppComponent.class获取ApiServiceModule类里的provideApiService方法得到的。不知道这么理解对不对?

对,就是这个意思!始终记得 Module 是那个最终生成实例的地方,Dagger 框架会主动去调用,这也是使用 Dagger 后,我们为什么不需要 new 那些实例的原因!

@bigggge
Copy link
Author

bigggge commented Sep 19, 2016

@maoruibin 那这个provideMainActivity方法呢?我试着删除provideMainActivity和provideApplication方法,程序还是可以正常运行,这是为什么?

@maoruibin
Copy link
Owner

你删除后 clear 了没

@bigggge
Copy link
Author

bigggge commented Sep 19, 2016

clean了 ,build文件夹也删了

@bigggge
Copy link
Author

bigggge commented Sep 19, 2016

@maoruibin 有Application getApplication(); 这句时才会报错,因为找不到返回Application的方法,但是代码里好像也没用到AppComponent中的getApplication()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants