当使用 'api' 添加库依赖项时,不提供对使用 Gradle 中的 'implementation' 声明的库的访问权限?

When library dependency is added using 'api' does not provide access to their library which is declared using 'implementation' in Gradle?

使用 'api' 在 App 模块中添加 LibA,使用 'implementation' 在 LibA 中添加 LibB。

我无法在应用程序中访问 LibB,它会出现编译错误。

谁能解释一下这里发生了什么?我是不是遗漏了什么或误解了 'api'、'implementation' 的概念?

解释可以参考Java Library plugin, especially in the API and Implementation separation章节的官方文档:

The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.

APi 配置的主要思想是避免库模块的内部依赖性泄漏到库消费者类路径中。

在你的例子中,LibB 被认为是对 LibA 的内部依赖,因为它是在 implementation 配置中定义的,因此你不应该访问 LibB直接在您的 App 模块中。

如果您需要使用 App 中的库 LibB,则只需使用 apiapi 声明从 AppLibB 的直接依赖项implementation配置。

api 依赖基本上是 传递 本质上仅对其上游项目。因此,在您的情况下,如果您希望 LibB 暴露给 App,那么您可以拥有这样的依赖项 -

App with implementation dependency to LibA and LibA with api dependency to LibB

这将允许 LibB 传递给 App

但是,人们应该谨慎地使用 api 依赖,并且只在需要的时候使用。