简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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