作者:淑香门蒂 | 来源:互联网 | 2023-02-07 19:15
我正在使用dagger2作为我的应用程序.我有一个模块,提供一些依赖,如Retrofit
,Gson
等.
NetModule.java
@Module
public class NetModule {
private String mBaseUrl;
public NetModule(String baseUrl) {
this.mBaseUrl = baseUrl;
}
@Provides
@Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
@Provides
@Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
@Provides
@Singleton
Gson provideGson() {
GsonBuilder gsOnBuilder= new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder()
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
return okHttpClient;
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
return retrofit;
}
}
NetComponent.java
@Singleton
@Component(modules = {AppModule.class, NetModule.class, Validator.class})
public interface NetComponent {
void inject(AuthenticationActivity authenticationActivity);
void inject(PaymentActivity paymentActivity);
}
AppApplication.java
@Override
public void onCreate() {
super.onCreate();
mNetCompOnent= DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://corporateapiprojectwar.mybluemix.net/corporate_banking/mybank/"))
.build();
}
这种方法一直有效,直到我的完整应用程序只有一个基本URL.现在我有一个不同的基地址AuthenticationActivity
和PaymentActivity
所以我不能在构造函数发送URL NetModule
中onCreate
的Application
任何人都可以帮助我如何使用dagger2添加动态基础改造Url.
1> caco3..:
您可以使用@Named
注释Dagger2用户指南(请参阅'限定符'部分'):
在NetModule.java中:
@Provides
@Singleton
@Named("authRetrofit")
public Retrofit provideAuthRetrofit() {
// setup retrofit for authentication
return retrofit;
}
@Provides
@Singleton
@Named("paymentRetrofit")
public Retrofit providePaymentRetrofit() {
// setup retrofit for payments
return retrofit;
}
在你的AuthenticationActivity
:
@Inject
@Named("authRetrofit")
Retrofit retrofit;
最后在你的PaymentActivity.java
:
@Inject
@Named("paymentRetrofit")
Retrofit retrofit;
然后,dagger将自动注入Retrofit
配置为PaymentActivity的付款,并Retrofit
配置为AuthenticationActivity中的身份验证