导语
依赖注入是一种面向对象的编程模式,它的出现是为了降低耦合性。可能有的人觉得之前并没有使用过依赖注入,其实当我们在类的构造函数中通过参数引入对象或通过set方法设置类的对象时,就是依赖注入。而通过注解的方式完成的依赖注入就是本篇要讲的Dagger库的使用。
添加依赖build.gradle
compile 'com.google.dagger:dagger:2.7'
annotationProcessor 'com.google.dagger:dagger-compiler:2.7'
*如果,build项目抛出“ Execution failed for task ':app:javaPreCompileDebug” 就在gradle中填写下面代码。
defaultConfig {
javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
}
如何使用
1、 创建Student类:
public class Student {
@Inject
public Student() {
}
}
Student类中有一个空的构造方法,并且在构造方法上面添加了一个@Inject注解。
然后,我们使用ctrl+F9(mac使用Cmd+F9)进行一次编译,查看项目路径:
app\build\generated\source\apt\debug\com\mei_husky\sample_dagger2\model\Student_Factory.java
会发现编译器自动生成了一个Student_Factory类:
@Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.gi