由于想实现MVP框架,看到dagger2使得参数获取变得如此简单,进而下手。
参考链接:
http://www.jianshu.com/p/cd2c1c9f68d4
或
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0519/2892.html
首先得搞清楚 Inject,Component,Module,Provides它们是什么?
一、Component
Component也是一个注解类,Component会查找目标类中用Inject注解标注的属性
二、Module
封装第三方类库的代码放入Module中
三、Component 与 Module关系
Component是注入器,Module是一个提供类实例的类,Component的新职责就是管理好Module
四、Provides
Module中的创建类实例方法用Provides进行标注,Component在搜索到目标类中用Inject注解标注的属性后,Component就会去Module中去查找用Provides标注的对应的创建类实例方法,这样就可以解决第三方类库用dagger2实现依赖注入了。
五、Singleton
Singleton(单例)
六、PerActivity
PerActivity是一个自定义的范围注解,作用是允许对象被记录在正确的组件中,当然这些对象的生命周期应该遵循activity的生命周期。
使用
一、build.gradle中配置
apply plugin: ‘com.neenbedankt.android-apt’
buildscript {
repositories {
jcenter()
}
dependencies {
classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.4’
}
}
android {
//解决 Dagger2/ButterKnife 冲突
packagingOptions {
exclude ‘META-INF/services/javax.annotation.processing.Processor’
}
}
dependencies {
apt ‘com.google.dagger:dagger-compiler:2.0’
compile ‘com.google.dagger:dagger:2.0’
…
}
二、Activity中初始化
mLoginComponent = DaggerLoginComponent.builder().appComponent(getAppComponent())
.loginModule(new LoginModule(LoginActivity.this, this))
.activityModule(new ActivityModule(this)).build();
mLoginComponent.inject(this);
三、Application初始化
mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
mAppComponent.inject(this);//必须有
四。在要使用的地方@Inject 使用
我的框架地址MVP+dagger2+Rxjava+Retrofit
https://github.com/llxqb/MyMVPDemo