我在这个类中进行改造的字段从未被注入,当我运行我的代码时它仍然是null。
这是我的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();
}
我的应用类:
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;
}
}
我试图摆弄代码,我似乎没有设法让它正常工作。我在这里错过了什么?
更新(以前的信息仍然有效):
我注意到你错误地构建了你的组件:你必须在.networkModule(new NetworkModule())
之后添加DaggerAppComponent.builder()
确保你的private AppComponent appComponent
也被初始化了!
对于场注入(我相信这就是你所追求的),你可以像这样写你的构造函数:
public ServiceClass(){
MyApplication.getInstance().getAppComponent().inject(this)
}
当然,您应该以某种方式公开您的appComponent实体 - 以上是我的猜测(通过应用程序实体公开appComponent实体)。
PS:更好的方法(也更具可读性)是完全避免场注入和参数化构造函数(但是并不总是这样,例如,如果你注入活动)。
PSS:你的AppComponent也应该有void inject(ServiceClass value);
在retrofit
有多种注射ServiceClass
的方法
Component
制作一个单独的ServiceClass
,如: -
@Component(dependencies = AppComponent.class)
interface ServiceClassComponent {
void injectServiceClass(ServiceClass serviceClass);
}
要么
ServiceClass
注入你的应用程序组件: -
void injectServiceClass(ServiceClass serviceClass);
进入你的AppComponent
dependencies
关键字将包含您要构建的特定组件中的所有依赖组件。
然后在ServiceClass
的构造函数中,您需要构建Component并注入它