前言
Dagger2进阶-范围的控制(Scope和Singleton)
Dagger2,中文翻译 “匕首”,是一把Android开发的致命武器,作为大项目开发中必不可少的利器,希望大家能耐心把文章一篇篇的耐心读完并且实践操作。
Dagger2的介绍:
Dagger2是用来做依赖注入的。通常我们理解为替代我们生成一堆供我们使用的对象,比如:我们想要ImageManager、NetWorkManager、DbManaer等对象,我们通过Dagger2配置好直接通过简单的注解就能得到对象,而且不用考虑ImageManger等对象里面的构造方法所需要依赖的参数,框架直接帮我们配置好,我们只需要关注最外部的对象就可以了。比较简单的理解就是,Dagger2是为生成对象减少我们new的工作而生的,是为了替代工厂类而缔造的,当然Dagger2的原理也是用到了工厂类,这我们后面再说。
AndroidStudio的坏境配置
Dagger2在As的配置有两种方式:分别是apt和annotationProcessor,这里强烈推荐使用annotationProcessor,因为apt在as2.2之后谷歌已经暂停,annotationProcessor支持jack方式和javac方式编译,而apt只支持javac,当使用apt会出现一些跟其他注解框架冲突等不可见的问题。
APT配置
第一步:在项目的build.gradle文件中添加apt插件到as中
dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }
第二步:讲apt插件引入到Module项目的build.gradle
apply plugin: 'com.neenbedankt.android-apt' dependencies { compile 'com.google.dagger:dagger:2.7' apt 'com.google.dagger:dagger-compiler:2.7' compile 'org.glassfish:javax.annotation:10.0-b28' }
最后编译就可以使用dagger2了。
这里解释一下classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'、apply plugin: 'com.neenbedankt.android-apt'、 compile 'org.glassfish:javax.annotation:10.0-b28'是为了引入Apt插件的,真正跟其他注解框架不同的只是 compile 'com.google.dagger:dagger:2.7'这个dagger包。
AnnotationProcessor
annotationProcessor使用非常简单只需要在各个module的build.gradle中依赖一下代码
compile 'com.google.dagger:dagger:2.7' annotationProcessor 'com.google.dagger:dagger-compiler:2.7'
这里的'com.google.dagger:dagger:2.7'也是dagger包,里面有专属于dagger2的注解等工具类。annotationProcessor这个是Module根据注解生成代码的工具。
常见问题
1:在多Module中的时候,很多小朋友说,只有主Module才有效,子Module不生效,原因是因为每个Module都应该添加
annotationProcessor 'com.google.dagger:dagger-compiler:2.7'
加入不添加的module是不能自动生成代码的。