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

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

问题描述

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

我在build.gradle中尝试这个:

 任务setenv(类型:Exec){
commandLineexport,SOME_TEST_VAR = aaa
}
test.dependsOn setenv

且构建失败:


执行失败的任务':myproject:setenv'。


启动进程'command'export''



我也试过这个:

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

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

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

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



更新:

确实通过了,我的测试任务收到了一切,无论是systemProperty,环境变量还是jvmArgs。



所以,Gradle本身在这里没什么问题。

当我在真正的项目中尝试它时,问题就出现了。它使用Spring进行依赖注入。我可能是错的,但它看起来像Spring框架清除这些值的地方。

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

解决方案

对于测试任务,您可以使用 environment property 像这样:

  test {
environmentVAR,val
}

您也可以使用环境属性在执行任务中

 任务dropDatabase(类型:Exec){ 
environmentVAR,val
commandLinedoit
}

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


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

I'm trying this in my build.gradle:

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

and the build fails:

Execution failed for task ':myproject:setenv'.

A problem occurred starting process 'command 'export''

I also tried this:

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

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

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

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

Update:

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.

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

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"
}

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天全站免登陆