问题描述
我可以肯定这种情况很普遍,但是在任何教程中都没有找到解决方案。也许我完全以错误的方式来解决这个问题。
我有一个提供翻新服务的模块:
public static RestService providesRestService(){
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.somedomain.com")
.addConverterFactory(GsonConverterFactory.create()).build();
return retrofit.create(RestService.class);
}
我希望基本URL可通过属性文件进行配置。要使用属性文件,我需要上下文,以便可以访问AssetManager:
AssetManager assetManager = context.getAssets();
assetManager.open("somefile.properties")
...
所以我可以使用@ApplicationContext批注:
public static RestService providesRestService(@ApplicationContext){
并且应该可以获取属性,但是问题是我还有另一个模块,提供了一个用于处理属性文件的类:
static PropertiesUtil providesPropertiesUtil(@ApplicationContext Context context) {
return new PropertiesUtil(context);
所以我想使用该类,但无法将PropertiesUtil注入另一个provider方法。
我把这一切都弄错了吗?
解决方法
我全都错了。更好的方法(在我看来是因为您不需要处理Context)是使用buildConfig变量。
在我添加的app / build.gradle文件中:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
buildConfigField "String","REST_BASE_URL",RELEASE_REST_BASE_URL
}
debug {
applicationIdSuffix ".debug"
debuggable true
buildConfigField "String",DEV_REST_BASE_URL
}
}
这将创建一个静态String变量,您可以通过自动生成的BuildConfig.REST_BASE_URL来访问
您可以添加一个app / gradle.properties文件以具有以下内容:
DEV_REST_BASE_URL="http://dev.example.com"
RELEASE_REST_BASE_URL="http://example.com"
Gradle会使用确切的值来生成文件,因此必须添加引号,否则BuildConfig.java将如下所示:
公共静态字符串REST_BASE_URL = http://example.com;
代替
公共静态字符串REST_BASE_URL =“ http://example.com”;