我在这个类中用于翻新的字段从未被注入,当我运行我的代码时,它仍然是空的。
下面是我的ServiceClass,为了简单起见,我在其中注入了翻新,调用了我的api。
public class ServiceClass{
@Inject
Retrofit retrofit;
public ServiceClass(){
}
}所有与网络相关的依赖项的模块类:
@Module
public class NetworkModule {
@Provides
@ApplicationScope
Retrofit getRetrofit(OkHttpClient okHttpClient, Gson gson){
return new Retrofit.Builder()
.baseUrl(URL.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@Provides
@ApplicationScope
OkHttpClient getOkHttpClient(Gson gson, HttpLoggingInterceptor httpLoggingInterceptor){
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder().addInterceptor(httpLoggingInterceptor);
return okHttpClient;
}
@Provides
@ApplicationScope
HttpLoggingInterceptor getHttpLoggingInterceptor(){
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
}
@Provides
@ApplicationScope
Gson getGson(){
return new Gson();
}
}我的AppComponent这是我唯一的组件类:
@ApplicationScope
@Component(modules = {NetworkModule.class})
public interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(MyApplication myApplication);
AppComponent build();
}
void inject(MyApplication myApplication);
Retrofit getRetrofit();
}我的Application类:
public class MyApplication extends Application{
private AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent
.builder()
.application(this)
.build()
.inject(this);
}
public AppComponent getAppComponent(){
return appComponent;
}
}我试着摆弄代码,但似乎没能让它正常工作。这里我漏掉了什么?
发布于 2019-03-09 03:03:53
更新(以前的信息仍然有效):
我注意到你错误地构建了你的组件:你必须在DaggerAppComponent.builder()之后添加.networkModule(new NetworkModule()),确保你的private AppComponent appComponent也被初始化了!
对于字段注入(我相信这就是你想要的),你可以这样写你的构造函数:
public ServiceClass(){
MyApplication.getInstance().getAppComponent().inject(this)
}当然,您应该以某种方式公开您的appComponent实体-上面是我的猜测(通过应用程序实体公开appComponent实体)。
附注:更好的方法(也更具可读性)是完全避免字段注入,并参数化构造函数(然而,这并不总是可能的,例如,如果你注入到activity中)。
另外:你的AppComponent也应该有void inject(ServiceClass value);
发布于 2019-03-09 03:10:32
在ServiceClass中有多种注入retrofit的方式
ServiceClass创建一个单独的Component,如下所示:-@Component(dependencies = AppComponent.class)接口ServiceClassComponent { void injectServiceClass(ServiceClass serviceClass);}
或
ServiceClass注入到您的应用程序组件中:-serviceClass); injectServiceClass(ServiceClass void
进入你的AppComponent
dependencies关键字将包含您要构建的特定组件中的所有依赖组件。
然后,在ServiceClass的构造函数中,您需要构建组件并注入它
https://stackoverflow.com/questions/55069267
复制相似问题