我在我的应用程序中使用dagger2
。我已经在我的整个应用程序中创建了模块,组件,所以我在application
类中初始化它。
下面是我的模块,dagger2的组件,它有助于解决依赖关系。
NetComponent.java
@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
void inject(AuthenticationActivity authenticationActivity);
void inject(PaymentActivity paymentActivity);
}
AppModule.java
@Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
Application providesApplication() {
return application;
}
}
NetModule.java
@Module
public class NetModule {
@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
@Named("authRetrofit")
Retrofit provideAuthRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(PAYMENT_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
@Provides
@Singleton
@Named("paymentRetrofit")
Retrofit providePaymentRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(LOGIN_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
}
AppApplication.java
public class AppApplication extends Application {
private NetComponent mNetComponent;
@Override
public void onCreate() {
super.onCreate();
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.build();
}
public NetComponent getmNetComponent() {
return mNetComponent;
}
}
Validator.java
@Module
public class Validator {
@Provides
com.mobsandgeeks.saripaar.Validator providesValidator(Application application) {
return new com.mobsandgeeks.saripaar.Validator(application);
}
}
我想将活动实例传递给我正在使用它的Validator
的构造函数。
假设我想在Validator
中注入MainActivity.java
,那么构造函数应该有MainActivity
个实例。
我应该采取什么方法?我应该在activity
中为此初始化匕首依赖关系吗?我是否需要为此创建新组件?
答案 0 :(得分:1)
您可以简单地为ValidatorModule创建构造函数:
let uinput = 'éTelkhd sfhe lRR';
console.log('#1 -> ', uinput.toLowerCase());
console.log('#2 -> ', uinput.toLowerCase().normalize('NFD'));
让我知道你是否正在寻找