2个不同的对象,一个类与Dagger

时间:2018-04-23 10:04:03

标签: android dagger

我需要模块返回2个不同的对象Retrofit 如何让组件区分这些对象Retrofit?

代码改造

@Provides
public Retrofit provideRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl("google.com"))
            .client(okHttpClient)
            .build();
}

对象仅在.baseUrl()

中有所不同

1 个答案:

答案 0 :(得分:0)

对于具有相同类的依赖项,您可以使用@Named

@Provides @Named("foo") String provideFoo() {
    return "foo string";
}

注入:

public class SomeClass {
    @Inject @Named("foo") String fooString;

    @Inject public SomeClass() {
        System.out.println("value of fooString is " + fooString);
    }
}

你的案子:

@Provides @Named("google")
public Retrofit provideRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl("google.com"))
            .client(okHttpClient)
            .build();
}

@Provides @Named("so")
public Retrofit provideRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) {
    return new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl("stackoverflow.com"))
            .client(okHttpClient)
            .build();
}