如何通过Dagger让Component区分两个仅BaseUrl不同的Retrofit实例?
区分Dagger中同类型不同配置的Retrofit实例
嘿,这个场景我太熟悉了!要让Dagger区分两个仅BaseUrl不同的Retrofit实例,核心思路是用**限定符(Qualifier)**来标记不同的实例,常用的有两种实现方式,给你一步步讲清楚:
方法一:使用@Named注解(快速实现)
@Named是Dagger自带的限定符,通过字符串标识不同实例,适合快速开发:
1. 修改Module中的Provide方法
给每个Retrofit的提供方法加上@Named注解,用不同的字符串区分:
@Provides @Named("google_retrofit") public Retrofit provideGoogleRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("https://google.com") // 记得加http/https前缀 .client(okHttpClient) .build(); } @Provides @Named("other_retrofit") public Retrofit provideOtherRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("https://your-other-domain.com") .client(okHttpClient) .build(); }
2. 注入时指定对应的@Named标识
在需要注入Retrofit的地方,同样用@Named标注你要的实例:
@Inject @Named("google_retrofit") Retrofit googleRetrofit; @Inject @Named("other_retrofit") Retrofit otherRetrofit;
方法二:自定义Qualifier注解(更优雅、更安全)
如果怕字符串拼写错误,或者以后要扩展更多Retrofit实例,自定义Qualifier注解是更好的选择:
1. 定义自定义Qualifier注解
创建两个注解类,分别标记不同的Retrofit实例:
@Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface GoogleRetrofit { } @Qualifier @Retention(RetentionPolicy.RUNTIME) public @interface OtherRetrofit { }
2. 修改Module中的Provide方法
用自定义注解替换@Named:
@Provides @GoogleRetrofit public Retrofit provideGoogleRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("https://google.com") .client(okHttpClient) .build(); } @Provides @OtherRetrofit public Retrofit provideOtherRetrofit(Context context, OkHttpClient okHttpClient, Gson gson) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("https://your-other-domain.com") .client(okHttpClient) .build(); }
3. 注入时使用自定义注解
这样注入时就不会有拼写错误的风险了:
@Inject @GoogleRetrofit Retrofit googleRetrofit; @Inject @OtherRetrofit Retrofit otherRetrofit;
小提示
- 一定要给BaseUrl加上
http://或https://,不然Retrofit会抛出非法URL的异常 - 如果你的OkHttpClient或Gson也有不同配置,同样可以用这两种方式区分实例
内容的提问来源于stack exchange,提问作者user8940426
相关产品推荐
相关产品推荐

