如何从 Gradle 构建中设置环境变量? [英] How to set an environment variable from a Gradle build?

查看:70
本文介绍了如何从 Gradle 构建中设置环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 Gradle 构建中设置一个环境变量.我在 MacOS X (El Capitan) 上.命令是gradle test".

I'm trying to set an environment variable from my Gradle build. I'm on MacOS X (El Capitan). The command is "gradle test".

我正在我的 build.gradle 中尝试这个:

I'm trying this in my build.gradle:

task setenv(type: Exec) {
    commandLine "export", "SOME_TEST_VAR=aaa"
}
test.dependsOn setenv

构建失败:

任务 ':myproject:setenv' 执行失败.

Execution failed for task ':myproject:setenv'.

启动进程'command 'export''时出现问题

A problem occurred starting process 'command 'export''

我也试过这个:

test.doFirst {
    ProcessBuilder pb1 = new ProcessBuilder("export SOME_TEST_VAR=some test value")
    pb1.start();
}

构建成功.但是,如果我在 JUnit 测试中检查环境变量,它会失败:

The build succeeds. However, if I check the environment variable in my JUnit test it fails:

assertTrue(System.getenv().containsKey("SOME_TEST_VAR"));

有没有办法从 Gradle 构建中设置环境变量(在 build.gradle 文件中)?

Is there any way to set an environment variable from a Gradle build (in the build.gradle file)?

更新:

我已经单独对其进行了测试:值确实通过了,我的测试任务接收了所有内容,无论是 systemProperty、环境变量还是 jvmArgs.

I've tested it in isolation: the values do get passed and my test task receives everything, be it a systemProperty, environment variables or jvmArgs.

所以,这里的 Gradle 本身并没有什么问题.

So, it's nothing wrong with Gradle itself here.

当我在实际项目中尝试时,问题就出现了.它使用 Spring 进行依赖注入.我可能错了,但看起来 Spring 框架在某处清除了这些值.

The problem arises when I'm trying it on the real project. It uses Spring for dependency injection. I may be wrong but it looks like the Spring framework purges those values somewhere.

该子项目目前被冻结,我现在无法详细检查我的猜测.

That sub-project is currently being frozen and I can't check my guess in detail right now.

推荐答案

对于测试任务,可以使用 环境属性 像这样:

For a test task, you can use the environment property like this:

test {
  environment "VAR", "val"
}

您还可以使用 环境属性 在 exec 任务中

you can also use the environment property in an exec task

task dropDatabase(type: Exec) {
    environment "VAR", "val"
    commandLine "doit"
}

请注意,使用此方法,环境变量仅在任务期间设置.

Note that with this method the environment variables are set only during the task.

这篇关于如何从 Gradle 构建中设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆