如何使用dagger2在改造模块中添加动态基本URL

时间:2017-04-01 20:49:00

标签: java android dagger-2

我正在使用dagger2作为我的应用程序。我有一个模块,它提供了一些依赖项,如RetrofitGson等。

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();

}

这种方法一直有效,直到我的完整申请只有一个基本网址。现在我为AuthenticationActivityPaymentActivity提供了不同的基本网址,因此我无法在NetModule onCreate的{​​{1}}的{​​{1}}的构造函数中发送网址

任何人都可以帮助我如何使用dagger2添加动态改进的Url改造。

1 个答案:

答案 0 :(得分:5)

您可以使用@Named注释Dagger2 user guide(请参阅“限定符”部分):

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