Gradle几种引入依赖的方式介绍

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 类似,runtimeruntimeOnlyDeprecated 版。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 的方式才会同时作用于 compileruntime ,同理, compileOnlyApi 就是只作用于 compile

plugins {
	id 'java-library'
	id 'maven-publish' // 使用这个插件打包
}
// ... 其他配置省略
dependencies {
	// 这个引入是为了说明 api 和其他方式的区别
	api("org.apache.commons:commons-lang3:3.8.1")
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值