如何将属性设置为可从Java代码执行的Groovy脚本? [英] How to set properties to Groovy script which is executable from Java code?

查看:278
本文介绍了如何将属性设置为可从Java代码执行的Groovy脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Groovy脚本中,我有这样的代码:

  def username = System.getenv()['USER'] 
def password = System.getenv()['PASS']

这是因为我可以将此信息用作Groovy脚本的参数,因为其他用户不应该知道它。当我运行这个脚本时,我在我的系统中设置了这个参数。现在我有一个问题。我有一个远程运行Groovy脚本的Java应用程序。有什么方法可以在Java代码中设置环境变量? (这里我发现这是不可能的)。或者是否有一些安全的方法可以将这些属性从Java发送到Groovy?

解决方案

如果您正在启动Groovy脚本, Runtime.exec (或类似)的最小公分母,那么您可以在其中一个重载方法


在指定环境的单独进程中执行指定的字符串命令。



...


$ b

envp - 字符串数组,其中的每个元素都具有格式名称的环境变量设置= value;如果子进程应该继承当前进程的环境,则为null。


如果另一方面调用Groovy脚本在同一个Java进程中,那么它将具有与之相同的属性正在运行的过程。因此,在调用Groovy脚本之前调用 System.setProperty(USER,xxx)将意味着该属性对您的Groovy逻辑可见。






您应该注意环境是操作系统级别的东西;如果您正在寻找应用程序级别的设置,您应该检查 System.properties 代替。


In my Groovy script I have this code:

def username = System.getenv()['USER']
def password = System.getenv()['PASS']

It is because I can't use this information as parameter to Groovy script, because other users shouldn't know it. When I run this script I set this parameter in my system. Now I have a problem. I have a Java application which runs Groovy script remotely. Is there some way that I can set enviromental variable in Java code? (Here I found that it isn't possible). Or is there some safe ways to send this properties from Java to Groovy?

解决方案

If you're launching the groovy script by the lowest common denominator of Runtime.exec (or similar), then you can specify the environment in one of the overloaded methods:

Executes the specified string command in a separate process with the specified environment.

...

envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

If on the other hand you're invoking the Groovy script within the same Java process, then it will have the same properties as the running process. So simply calling System.setProperty("USER", xxx) before invoking the Groovy script will mean this property is visible to your Groovy logic.


You should note that the environment is an operating-system level thing; a measure of the properties of the OS on which the process is running.

If you're looking for application-level settings, you really ought to be checking System.properties instead.

这篇关于如何将属性设置为可从Java代码执行的Groovy脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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