基于已有的项目结构引入Dagger,不能完全按照项目的架构去写,只能是增加引入Dagger。
环境搭建
1,gradle中增加插件android-apt
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'//看这里,看这里,看这里 }}allprojects { repositories { jcenter() }}task clean(type: Delete) { delete rootProject.buildDir}
2,gradle中应用插件
apply plugin: 'com.neenbedankt.android-apt'//这里应用插件dependencies { //dagger apt 'com.google.dagger:dagger-compiler:2.11' provided 'org.glassfish:javax.annotation:10.0-b28' compile 'com.google.dagger:dagger:2.11' compile 'com.google.dagger:dagger-android:2.11' compile 'com.google.dagger:dagger-android-support:2.11' apt 'com.google.dagger:dagger-android-processor:2.11'}
3,增加一个继承DaggerApplication的类App
public class App extends DaggerApplication { @Override protected AndroidInjector applicationInjector() { return DaggerAppComponent.builder().build(); }}
4,创建AppComponent
@Singleton@Component(modules = {ActivityBindModule.class, AndroidSupportInjectionModule.class})public interface AppComponent extends AndroidInjector{}
5,创建AndroidBindModule,配置需要使用Dagger的Activity(继承DaggerAppCompatActivity)
@Modulepublic abstract class ActivityBindModule { @ContributesAndroidInjector(modules = {HomeModule.class, DashboardModule.class, NotificationsModule.class}) abstract MainActivity mainActivity();}
6,创建HomeModule
@Modulepublic abstract class HomeModule { @ContributesAndroidInjector abstract HomeFragment fragment(); @Provides static HomePresenter homePresenter() { return new HomePresenter(); }}
遗留问题:
1,HomeFragment中presenter的声明是HomePresenter,不是IContract.IPresenter
2,未引入@ActivityScoped,@FragmentScoped
小结:
- @Inject标注的属性不能是private
- @Provides标注的方法不能是抽象方法
- @Component标注的接口至少有一个方法,否则编译不会生成实现类