You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何指定仅生产运行时生效、测试运行时不可用的runtimeOnly依赖?

实现runtimeOnly依赖仅在生产运行时生效的方法

当然有可行方案,针对Gradle构建的项目,你可以通过以下两种方式实现:

  • 方法一:在测试运行时配置中排除目标依赖
    Gradle默认的testRuntimeOnly配置会继承runtimeOnly的所有依赖,所以只需在testRuntimeOnly里明确排除你不想在测试环境加载的库即可。示例代码:

    dependencies {
        runtimeOnly 'com.example:production-lib:1.0.0'
        testRuntimeOnly {
            exclude group: 'com.example', module: 'production-lib'
        }
    }
    
  • 方法二:自定义生产专属的运行时配置
    要是想更清晰地区分生产和测试的依赖范围,你可以单独定义一个生产专用的配置,仅关联生产运行任务,不纳入测试任务的类路径:

    // 自定义生产运行时配置,继承默认runtimeOnly的基础依赖
    configurations {
        productionRuntimeOnly.extendsFrom runtimeOnly
    }
    
    dependencies {
        // 将生产专属依赖绑定到自定义配置
        productionRuntimeOnly 'com.example:production-lib:1.0.0'
    }
    
    // 让生产运行任务(比如run)包含该自定义配置的依赖
    tasks.named('run') {
        classpath += configurations.productionRuntimeOnly
    }
    
    // 确保所有测试任务都不包含这个生产专属配置
    tasks.withType(Test) {
        classpath -= configurations.productionRuntimeOnly
    }
    

如果使用Kotlin DSL,只需把Groovy语法调整为对应的Kotlin写法即可,核心逻辑完全一致。

内容的提问来源于stack exchange,提问作者Nikola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:35:22