android dagger2 自定义

先定义两个Qualifier,待会在Module中用于区分两个Person

1
2
3
4
5
6
7

@Retention(RetentionPolicy.RUNTIME)
public @interface QualifierStudent {}


@Retention(RetentionPolicy.RUNTIME)
public @interface QualifierTeacher {}

Click and drag to move

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public interface  {
String saySomething();
}

public class Student implements {

public String name;

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

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

public class Teacher implements {

public String name;

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

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

Click and drag to move

这里是重点,用上面定义的两个Qualifier @QualifierStudent和@QualifierTeacher来区分两个放回类型都为Person的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Module
public class MainModule {

@Provides
@QualifierStudent
public Person provideStudent() {
return new Student();
}

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

Click and drag to move

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

Click and drag to move

这里是另一个重点,被注入的变量也要用Qualifier标注,表示要用那个方法来生成对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MainActivity extends AppCompatActivity {

@Inject
@QualifierTeacher
Person person;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

DaggerMainActivityComponent.create().inject(this);
TextView textView = findViewById(R.id.text);
textView.setText(person.saySomething());
}
}

Click and drag to move