compileOnly
使用 compileOnly 引入的依赖对于我们的代码能顺利编译通过是必需的一部分,但是这部分依赖通常在代码运行时(runtime)是不必需的;为了减少编译后的代码体积,可以使用 compileOnly 引入依赖。比如: lombok 。
implementation | compile
这两个方法的效果是一样的,只是新版的 Gradle 中建议使用 implementation 。
原话如下:
Why no compile configuration?
The Java Library Plugin has historically used the compile configuration for dependencies that are required to both compile and run a project’s production code. It is now deprecated, and will issue warnings when used, because it doesn’t distinguish between dependencies that impact the public API of a Java library project and those that don’t. You can learn more about the importance of this distinction in Building Java libraries.
摘自:Building Java & JVM projects
这两个方法不用介绍,使用他们引入的依赖从编译到运行时都会包含在我们的代码中。
runtimeOnly | runtime
同 compile 类似,runtime 是 runtimeOnly 的 Deprecated 版。runtimeOnly 表示引入的依赖不参与编译,只在运行时才用得到。比如: 数据库驱动 。
testCompilyOnly / testImplementation / testRuntimeOnly
功能分别对应:compileOnly, implementation, runtimeOnly ,只是仅限于 test 单元测试中使用。
api / compileOnlyApi
假设你开发了一个工具包,你想将这个工具包打包成 jar 文件使得其他人可以使用,一般可以这样做:
plugins {
id 'java-library'
id 'maven-publish' // 使用这个插件打包
}
// ... 其他配置省略
dependencies {
// 这个引入是为了说明 api 和其他方式的区别
implementation("org.apache.commons:commons-lang3:3.8.1")
}
执行以下命令即可在项目目录下的 build/libs 下发现打好的 jar 文件。
gradle clean publishToMavenLocal
此时将 jar 包拷贝给别人的 lib 目录下使用,发现对方无法使用 org.apache.commons:commons-lang3 包下的工具类,需要手动引入一下才行。因为用 implementation 方式引入的依赖在打包后只作用于 runtime ,只有使用 api 的方式才会同时作用于 compile 和 runtime ,同理, compileOnlyApi 就是只作用于 compile 。
plugins {
id 'java-library'
id 'maven-publish' // 使用这个插件打包
}
// ... 其他配置省略
dependencies {
// 这个引入是为了说明 api 和其他方式的区别
api("org.apache.commons:commons-lang3:3.8.1")
}
本文探讨了Gradle中的compileOnly, runtimeOnly, api等配置,解释了它们如何影响代码编译和运行,重点在于理解库依赖的区分和在打包过程中的不同作用。通过实例说明了library项目中使用api vs implementation的必要性。
759

被折叠的 条评论
为什么被折叠?



