參考
Android_Dagger2篇——從小白最易上手的角度 + 最新dagger.android
都是套路——Dagger2沒有想象的那麼難
一、無module方式,無參構造
(最簡單,但是不常用)
1. 在需要實例化的類中,構造無參構造方法,註解@Inject
必須是無參構造方法
@Inject
public Student() {
}
2. 構造Component接口,有inject方法
@Component
public interface DaggerComponent {
void inject(MainActivity activity); //要注入的類
}
3. Make Project (Ctrl+F9)
4. 在需要注入的類中調用
@Inject
Student mStudent;
DaggerStudentComponent.create().inject(this); //該方法執行成功即可以調用對象
二、有module方式
1. 在需要實例化的類中,構造方法註解@Inject
可以帶有參數
@Inject
public Student(String name, int age) {
this.name = name;
this.age = age;
}
2. 構造Module類
- 註解
@Module
- 構造一個返回類型爲需要注入對象的方法,註解
@Provides
@Module
public class StudentModule {
@Provides
Student provideStudent() {
return new Student("張三", 18);
}
}
3. 構造Component接口,有inject方法
@Component(modules = StudentModule.class) //與上面唯一的區別在此
public interface StudentComponent {
void inject(MainActivity activity);
}
4. 在需要注入的類中調用
使用builder方式而不是create注入
@Inject
Student mStudent;
DaggerStudentComponent.builder().studentModule(new StudentModule()).build().inject(this);
注意
@Inject
只能註解一個構造方法@Module
級別高於@Inject
@Component
可以標註接口
,也可以標註抽象類