Android Dagger2 构造方法参数注入

在上一篇文章Dagger2最简单的入门我们写了一个最简单的demo来介绍Dagger2,我们通过@Inject注解构无参造器来注入对象

那么如果构造器有参数,且这个参数也需要注入,又该怎么写呢?

本篇基于上一篇文章Dagger2最简单的入门,代码片段也是以上一篇文章的demo修改的,所以看本篇之前先看上一篇

我们先增加一个Teacher类,其中的无参构造方法用@Inject标识

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Teacher {

public String name;

@Inject
public Teacher() {
this.name = "苍老湿";
}

public Teacher(String name) {
this.name = name;
}

@Override
public String toString() {
return String.format("我的名字叫%s啦", name);
}
}

Click and drag to move

然后修改Student类原来的无参构造方法,增加一个Teacher参数,在toString()中增加显示老师的信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Student {

public String name;
public Teacher teacher;

@Inject
public Student(Teacher teacher) {
this.name = "野猿新一";
this.teacher = teacher;
}

public Student(String name) {
this.name = name;
}

@Override
public String toString() {
return String.format("我的名字叫%s啦,我们老师的名字叫%s", name, teacher.name);
}
}

Click and drag to move

ok,大工告成,就上面两步,直接运行看看

可以看到,注入Student对象的同时,也成功注入了Teacher对象

imgClick and drag to move

我们还是看下Dagger生成代码的注入流程

在MainActivity中调用如下代码

1
DaggerMainActivityComponent.create().inject(this);

Click and drag to move

DaggerMainActivityComponent中innect()方法再调用injectMainActivity()方法

injectMainActivity()方法内部调用了MainActivity_MembersInjector.injectStudent(),传入了activity对象和通过getStudent()方法获取的Student对象

我们看到getStudent()方法中直接new了一个Teacher对象,然后作为参数再new一个Student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
public void inject(MainActivity activity) {
injectMainActivity(activity);
}

@CanIgnoreReturnValue
private MainActivity injectMainActivity(MainActivity instance) {
MainActivity_MembersInjector.injectStudent(instance, getStudent());
return instance;
}

private Student getStudent() {
return new Student(new Teacher());
}

Click and drag to move

最后看下MainActivity_MembersInjector的injectStudent()方法,直接将传入student赋值给activity的student成员变量,至此就成功把Student注入到MainActivity中

1
2
3
public static void injectStudent(MainActivity instance, Student student) {
instance.student = student;
}

Click and drag to move