Gradle: 类路径和编译依赖有什么区别?

Gradle: What is the difference between classpath and compile dependencies?

在向我的项目添加依赖项时,我永远不确定应该给它们什么前缀,例如"classpath""compile".

例如,我下面的依赖项应该是编译时还是类路径?

此外,这应该在我的 applications build.gradle 中还是在 module 特定的 build.gradle 中?

当前build.gradle(应用级别):

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.hibernate:hibernate-core:5.0.5.Final'
    compile 'mysql:mysql-connector-java:5.1.38'
} 

我猜你在 dependencies {} 块中引用了 compileclasspath。如果是这样,这些就是依赖性 Configurations.

A configuration is simply a named set of dependencies.

compile 配置由 Java 插件创建。 classpath 配置在 buildSrc {} 块中很常见,其中需要声明 对 build.gradle 的依赖关系, 本身(对于插件,也许)。

如果 buildscript 本身需要一些东西到 运行,使用 classpath.

如果您的项目需要运行,请使用编译

buildscript{} 块用于 build.gradle 本身。

对于多项目构建,顶层构建文件针对根项目,具体构建文件针对子项目(模块)。

顶级构建文件,您可以在其中添加所有 sub-projects/modules.

通用的配置选项

不要将应用程序依赖项放在顶级构建文件中,它们属于单独的模块 build.gradle 文件

如果我没理解错的话,你是在混淆 Project.dependencies 脚本块和 Project.buildscript.dependencies 脚本块(就像我遇到这个问题时所做的那样)。

我会尝试用我发现的来回答这个问题。

我想您应该已经熟悉 Project.dependencies 脚本块了。在此块中,我们声明源代码所需的依赖项。有几种方法可以声明我们需要的项目依赖项。参见 Gradle Tutorial: Dependency Types。我只会提到与这个问题最相关的部分:

compile 'org.hibernate:hibernate-core:5.0.5.Final' 是模块依赖声明。编译配置(现在已被实现配置弃用。)只是 Implementation only dependencies. 的关键字它不是描述依赖类型的关键字(这里按类型我遵循定义的三种类型教程,即模块、文件和项目。)

Gradle Tutorial: Organizing Build Logic 中说:

If your build script needs to use external libraries, you can add them to the script’s classpath in the build script itself. You do this using the buildscript() method, passing in a closure which declares the build script classpath.

This is the same way you declare, for example, the Java compilation classpath. You can use any of the dependency types described in Dependency Types, except project dependencies.

Having declared the build script classpath, you can use the classes in your build script as you would any other classes on the classpath.

我希望你现在明白了。

对于 classpath "com.android.tools.build:gradle:${Versions.android_gradle_plugin}",我们使用 com.android.tools.build:gradle:${Versions.android_gradle_plugin} 设置 classpath 方法,这是构建脚本本身使用的模块依赖项,而不是项目中的源代码。

另一方面,对于 compile 'org.hibernate:hibernate-core:5.0.5.Final',我们通过编译 configuration.

声明您的项目所需的模块依赖性

tl;dr: classpathcompileimplementation 都是可以在不同情况下针对依赖项使用的关键字。前者在您想要将依赖项传递给构建脚本时使用,后者是您可能想要声明的 configuration 之一。

Android:

classpath in project build.gradle —— classpath之后的实现只被gradle自己使用,在构建脚本中使用。因此,如果我在项目 build.gradle 类路径 'retrofit...' 中添加实现(例如改造),我将无法在我的代码中进行改造!因为——我的代码看不到,只有buildscript可以看。

应用中的实现build.gradle——添加您的代码可以使用的实现!!