Android Dagger2 @Named用法

如下示例代码,在Module中同时提供了两个Person的实例,如果不加以区分,就会报如下错误

这时候我们可以在用@Name来加以区分

1
2
3
4
5
6
7
8
error: [Dagger/DuplicateBindings] com.him.hisapp.Person is bound multiple times:
@Provides com.him.hisapp.Person com.him.hisapp.MainModule.provideStudent()
@Provides com.him.hisapp.Person com.him.hisapp.MainModule.provideTeacher()

com.him.hisapp.Person is injected at
com.him.hisapp.MainActivity.person
com.him.hisapp.MainActivity is injected at
com.him.hisapp.MainActivityComponent.inject(com.him.hisapp.MainActivity)

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
32
33
34
35
36
37
38
39
40
41
public interface Person {
String saySomething();
}

public class Student implements Person {

public String name;

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

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

@Override
public String saySomething() {
return toString();
}
}

public class Teacher implements Person {

public String name;

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

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

@Override
public String saySomething() {
return toString();
}
}

Click and drag to move

重点在这里,用@Named来区分相同类的不同实例

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

@Provides
@Named("student")
public Person provideStudent() {
return new Student();
}

@Provides
@Named("teacher")
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

在具体要注入的地方也要通过@Named指定要注入哪一个

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

@Inject
@Named("student")
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