【发布时间】:2017-12-06 13:26:49
【问题描述】:
在搜索并尝试了太多事情之后,我陷入了一些看似简单的问题。 下面是我负责注入改造的模块。
@Module
public class NetworkingModule
{
@Provides
public Retrofit providesRetrofit()
{
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit;
}
}
我的网络组件
@Component( modules = NetworkingModule.class)
public interface NetworkingComponent {
void inject(DashboardPresenterImpl target);
void inject(PicksPresenterImpl picksPresenter);
void inject(LoadsPresenterImpl loadsPresenter);
void inject(ShippingPresenterImpl shippingPresenter);
void inject(GeneralFilePresenterImpl generalFilePresenter);
}
具有构造函数注入的实用程序类。请注意这个类也有 AppPreferences 的注入。
public class AppUtils {
private Context context;
@Inject
AppPreferences preferences;
@Inject
public AppUtils(@ActivityContext Context context)
{
this.context = context;
/*ActivityComponent component = DaggerActivityComponent.builder()
.activityModule(new ActivityModule((Activity) context))
.build();
component.inject(this);*/
}
}
现在在我的代码中我想实现这个
Class MyPresenterImpl{
@Inject
Retrofit retrofit;
@Inject
AppUtils appUtils;
}
请提出一种优化的好方法来实现上述目标。
编辑
添加 AppPreference.java
public class AppPreferences {
@Inject
SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Inject
public AppPreferences(@ActivityContext Context context)
{
ApplicationComponent component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule((Application) context.getApplicationContext()))
.build();
component.inject(this);
editor = sharedPreferences.edit();
}
public void putString(String key, String value)
{
editor.putString(key, value).commit();
}
public String getString(String key)
{
return sharedPreferences.getString(key, null);
}
}
【问题讨论】:
标签: android dependency-injection dagger-2