我的“ BaseServiceModule”是:

@Module
public class BaseServiceModule {

private static final int TIMEOUT = 40;
private static final int READ_TIMEOUT = 40;
private static final int WRITE_TIMEOUT = 40;

private String url = ServerData.getInstance().getServerUrl();


@Provides
String provideURL(){
    return url;
}

@Provides
Gson provideGson(){
    return new GsonBuilder().setLenient().create();
}

// Get BASE URL.
@Provides
public  Retrofit.Builder provideRetrofitBuilder(OkHttpClient okHttpClient) {
       return new Retrofit.Builder().baseUrl(ServerData.getInstance().getServerUrl()).client(okHttpClient);
}


// for custom URL, GSON
@Provides
public  Retrofit getCustomUrlInstance_Gson(Retrofit.Builder retrofitBuilder) {
    return retrofitBuilder.build();
}


@Provides
public  Retrofit.Builder getBuilderGson(Retrofit.Builder builder, GsonConverterFactory gsonConverterFactory) {
    return builder.addConverterFactory(gsonConverterFactory);
}

// GSON Converter Factory
@Provides
public GsonConverterFactory provideGsonConverterFactory( Gson gson){
    return GsonConverterFactory.create(gson);
}


@Provides
public OkHttpClient provideOkHttpClient() {
    return new OkHttpClient.Builder()
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            .build();
}

}


我的ServiceModule是:

@Module
public class ServiceModule {

  @Provides
  GlobalApiInterface provideGlobalApiInterfaceGson(Retrofit retrofit){
     return retrofit.create(GlobalApiInterface.class);
 }
}


我的ActivityComponent是:

@Component(dependencies = AppComponent.class, modules = ServiceModule.class)
public interface ActivityComponent {
    void inject(SchoolCodeActivity schoolCodeActivity);
}


我的AppComponent是:

@Component(modules = BaseServiceModule.class)
public interface AppComponent {
  Retrofit getRetrofitInstance();
  Retrofit.Builder getRetrofitBuilder();
 }


我的应用程序类是:

 public class MainApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
     AppComponent component = // not making "DaggerAppComponent" final class

  }
}


Dagger版本使用:

annotationProcessor "com.google.dagger:dagger-compiler:2.24"
implementation 'com.google.dagger:dagger-android-support:2.16'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.16'


我通过其他的DUPLICATE问题来寻求解决方案,但是找不到相关的解决方案。
我是Dagger的新手,我正在尝试在应用程序级别创建Retrofit实例,并在活动级别创建与Retrofit相关的接口。 “ GlobalApiInterface”是用于改造的接口,“ ServiceModule”是用于在改造中设置接口的模块。

请帮助我解决我犯错的地方。

最佳答案

实施匕首后,您至少需要构建和运行一次项目。它将自动生成DaggerAppComponent类

您能否尝试这种依赖关系:

implementation 'com.google.dagger:dagger:2.25.3'
annotationProcessor 'com.google.dagger:dagger-compiler:2.25.3'


gradle同步成功后,会使缓存无效并重新启动。然后运行您的项目。

08-18 14:39