如何提供相同类型的对象?匕首2 [英] How to provide objects of the same type? Dagger2

查看:78
本文介绍了如何提供相同类型的对象?匕首2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Dagger2 的新手,并试图构建这样的示例以了解其工作原理。

I am new at Dagger2 and tried to build such sample to understood how does it work.

有是我的示例代码:

MainActivity

public class MainActivity extends AppCompatActivity {

@Inject
protected ApiInterface apiInterface;

@Inject
protected Integer valueInt;

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

    App.getComponent().inject(this);
}

public void testButton(View view) {
    if (apiInterface == null || valueInt == null) {
        Log.e("TAG", "apiInterface == null");
    } else {
        Log.e("TAG", "apiInterface != null : " + apiInterface.value +  " : " + valueInt);
    }
 }
 }

组件

@Singleton
@Component(modules = {ModelModule.class, AnotherModule.class})
interface AppComponent {

void inject(MainActivity mainActivity);
}

模块

@Module
class ModelModule {

@Provides
int provideInt() {
    return 1;
}

@Provides
ApiInterface provideApiInterface(int i) {
    return ApiModule.getApiInterface(i);
}
}

模块

@Module
class AnotherModule {
@Provides
Integer getInt(){
    return 3;
}
}

如您在<$ c中的示例所示$ c> MainActivity 我注入 Integer

@Inject
protected Integer valueInt;

我也想使用 int 来为该方法提供值作为参数 provideApiInterface(int i)

and also i want to use int to provide value as argument for this method provideApiInterface(int i).

最终我得到了这样的错误

And eventually i get such error

Error:(11, 10) error: java.lang.Integer is bound multiple times:
@Provides int com.krokosha.aleksey.daggertwo.ModelModule.provideInt()
@Provides Integer com.krokosha.aleksey.daggertwo.AnotherModule.getInt()

我在做什么错了?

我应该如何以适当的方式提供此参数以避免这种错误?

How am i supposed to provide this argument in proper way to avoid such error?

推荐答案

您需要使用 限定符批注

You need to use qualifier annotations

@Module
class ModelModule {

    @Provides 
    @Named("FirstInt")
    int provideInt() {
        return 1;
    }
}

@Module
class AnotherModule {

    @Provides 
    @Named("SecondInt")
    int provideInt() {
        return 1;
    }
}

,并在注入依赖时使用此限定符

and use this qualifiers when injecting dependecies

@Inject
protected ApiInterface apiInterface;

@Inject 
@Named("FirstInt") //or whatever you need
protected int valueInt;

希望有帮助!
还请检查官方文档- http://google.github.io/dagger/

这篇关于如何提供相同类型的对象?匕首2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆