android dagger2

1
2
3
4
5
6
7

public class {
@Provides
public Teacher provideTeacher() {
return new Teacher();
}
}

Click and drag to move

MainModule通过includes包含TeacherModule

1
2
3
4
5
6
7
(includes = TeacherModule.class)
public class MainModule {
@Provides
public Person providePerson() {
return new Student();
}
}

Click and drag to move

这样MainActiviyComponent最后其实是引用了MainModule和TeacherModele两个Module

1
2
3
4
@Component(modules = MainModule.class)
public interface MainActivityComponent {
void inject(MainActivity activity);
}

Click and drag to move

以上其实和以下写法效果是一样的

1
2
3
4
5
6
7
@Component(modules = {
MainModule.class,
TeacherModule.class
})
public interface MainActivityComponent {
void inject(MainActivity activity);
}

Click and drag to move

当然Module的includes可以多层依赖的,比如TeacherModule还可以在includes其他Module,而且includes支持包含多个

1
2
3
4
5
6
7
8
9
10
(includes = {
FatherModule.class,
MotherModule.class
})
public class {
@Provides
public Teacher provideTeacher() {
return new Teacher();
}
}

Click and drag to move