You need to enable JavaScript to run this app. Android项目能否使用子模块依赖?为何依赖custom_retrofit模块仍需单独引入Retrofit
优惠活动
大模型
产品
解决方案
定价
更多

Android项目能否使用子模块依赖?为何依赖custom_retrofit模块仍需单独引入Retrofit

问题核心结论

你不需要在主项目A中单独引入Retrofit库,当前的编译报错,本质是Gradle依赖的传递规则配置不符合预期。

报错根因

  • Gradle中两种依赖关键字的传递能力有明确区别:
    • implementation:引入的依赖仅在当前模块的编译过程中可见,不会向外穿透传递到依赖当前模块的其他上层工程。
    • api:引入的依赖既可以在当前模块内部使用,也会传递到所有依赖当前模块的上层工程的编译类路径中。
  • 你在custom_retrofit子模块中引入Retrofit、OkHttp相关依赖时,统一用了implementation关键字,这些依赖的类索引只对custom_retrofit模块本身开放。哪怕主项目A通过api project(path:':custom_retrofit')引入了子模块,也拿不到这些被implementation隔离的第三方依赖。
  • 当你在主项目A的代码中直接调用Retrofit.Builder、GsonConverterFactory这类Retrofit内置类时,主项目的编译类路径里不存在这些类的定义,自然会抛出“需要引入Retrofit依赖”的编译提示。

正确修复方式

不需要在主项目A的依赖配置里重复添加Retrofit相关行,只需要调整custom_retrofit模块的Gradle配置即可:

  1. 把需要在上层主项目直接调用的Retrofit、OkHttp核心依赖,从implementation改成api,让依赖可以自动穿透传递到主项目:
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'

    // 核心Retrofit/OkHttp依赖改为api,支持向上层传递
    api 'com.squareup.retrofit2:retrofit:2.9.0'
    api 'com.squareup.retrofit2:converter-gson:2.9.0'
    api 'com.squareup.okhttp3:okhttp:4.9.0'
    api 'com.squareup.okhttp3:logging-interceptor:4.9.0'

    // 仅在子模块内部使用的依赖保留implementation即可,不对外暴露
    implementation('com.github.ihsanbal:LoggingInterceptor:3.1.0') {
        exclude group: 'org.json', module: 'json'
    }
}
  1. 同步Gradle配置后,主项目A的编译类路径就会自动包含Retrofit的相关类,可以直接正常调用,无需重复引入。

配置注意点

  • 不要把所有子模块的第三方依赖都统一改成api:只有确实需要在上层工程代码中直接调用的类对应的依赖,才需要用api传递;仅在子模块内部做封装、不对外暴露具体类的依赖,保留implementation可以减少不必要的类暴露、加快全工程的编译速度。
  • 主项目A当前的api project(path:':custom_retrofit')配置本身没有问题,不需要调整。

内容的提问来源于stack exchange,提问作者Amit Panchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 17:54:07