Dagger学习之实践篇

基于已有的项目结构引入Dagger,不能彻底按照项目android-architecture的架构去写,只能是增长引入Dagger。java

环境搭建android

1,gradle中增长插件android-aptgit

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中应用插件github

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<? extends DaggerApplication> applicationInjector() {
        return DaggerAppComponent.builder().build();
    }
}

4,建立AppComponentapp

@Singleton
@Component(modules = {ActivityBindModule.class, AndroidSupportInjectionModule.class})
public interface AppComponent extends AndroidInjector<App> {

}

5,建立AndroidBindModule,配置须要使用Dagger的Activity(继承DaggerAppCompatActivity)ide

@Module
public abstract class ActivityBindModule {
    @ContributesAndroidInjector(modules = {HomeModule.class, DashboardModule.class, NotificationsModule.class})
    abstract MainActivity mainActivity();
}

6,建立HomeModulegradle

@Module
public abstract class HomeModule {

    @ContributesAndroidInjector
    abstract HomeFragment fragment();

    @Provides
    static HomePresenter homePresenter() {
        return new HomePresenter();
    }
}

遗留问题:ui

1,HomeFragment中presenter的声明是HomePresenter,不是IContract.IPresentergoogle

2,未引入@ActivityScoped,@FragmentScoped

小结:

  • @Inject标注的属性不能是private
  • @Provides标注的方法不能是抽象方法
  • @Component标注的接口至少有一个方法,不然编译不会生成实现类
相关文章
相关标签/搜索