在Gradle中,我们可以使用implementation
、api
和testImplementation
等配置来管理依赖项。如果我们想要从最终工件(如jar)中排除某个依赖项,但在编译和运行单元测试时需要使用该依赖项,可以按照以下步骤进行操作:
dependencies
部分,将需要排除的依赖项配置为implementation
,表示它将被包含在最终工件中。implementation 'com.example:dependency:1.0.0'
configurations
块创建一个名称为excludeFromJar
的新配置,用于排除依赖项。configurations {
excludeFromJar
}
excludeFromJar
配置中,使用exclude
方法指定要排除的依赖项。configurations.excludeFromJar('com.example:dependency')
jar
任务中,使用from
方法和configurations
来指定要包含在最终工件中的内容,同时使用exclude
方法来排除excludeFromJar
配置中指定的依赖项。jar {
from sourceSets.main.output
from configurations.runtimeClasspath - configurations.excludeFromJar
}
test
任务中,使用dependencies
块将excludeFromJar
配置中排除的依赖项添加到testImplementation
配置中,以确保在编译和运行单元测试时使用该依赖项。test {
dependencies {
testImplementation configurations.excludeFromJar
}
}
完成以上步骤后,使用Gradle进行编译和运行单元测试时,excludeFromJar
配置中指定的依赖项将会被排除在最终工件之外,但仍然会在编译和运行单元测试时使用。
领取专属 10元无门槛券
手把手带您无忧上云