简体   繁体   English

如何将属性设置为可从Java代码执行的Groovy脚本?

[英]How to set properties to Groovy script which is executable from Java code?

In my Groovy script I have this code: 在我的Groovy脚本中,我有以下代码:

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. 这是因为我不能将此信息用作Groovy脚本的参数,因为其他用户不应该知道。 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. 我有一个Java应用程序,可以远程运行Groovy脚本。 Is there some way that I can set enviromental variable in Java code? 有什么方法可以在Java代码中设置环境变量? ( Here I found that it isn't possible). 在这里,我发现这是不可能的)。 Or is there some safe ways to send this properties from Java to Groovy? 还是有一些安全的方法可以将该属性从Java发送到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 : 如果要通过Runtime.exec的最低公分母(或类似文件)启动groovy脚本,则可以在重载的方法之一中指定环境:

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. envp字符串数组,其每个元素都具有名称=值格式的环境变量设置,如果子流程应该继承当前流程的环境,则为null。

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. 另一方面,如果您在同一Java进程内调用Groovy脚本,则它具有与正在运行的进程相同的属性。 So simply calling System.setProperty("USER", xxx) before invoking the Groovy script will mean this property is visible to your Groovy logic. 因此System.setProperty("USER", xxx)在调用Groovy脚本之前简单地调用System.setProperty("USER", xxx)将意味着该属性对您的Groovy逻辑是可见的。


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. 衡量运行该进程的OS的属性的一种方法。

If you're looking for application-level settings, you really ought to be checking System.properties instead. 如果要查找应用程序级别的设置,则实际上应该检查System.properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM