问题
I have a groovy script that uses a third party library. Each time I open the application and attempt to run my script I have to import the proper library.
I would like to be able to open GroovyConsole and run my application without having to import the library.
回答1:
In Linux you also have
/usr/share/groovy/conf/groovy-starter.conf
Here you can add your specific libs:
# load user specific libraries
load !{user.home}/.groovy/lib/*.jar
load /home/squelsh/src/neo4j-community-1.4.M03/lib/*.jar
load /home/squelsh/src/neo4j-community-1.4.M03/system/lib/*.jar
Hope it helps, had to search long time to find this (:
回答2:
If you just want to add the JARs to the classpath, copy (or symlink) them to ~/.groovy/lib
(or %USER_HOME%/.groovy/lib
on Windows).
If you want the actual import
statements to run every time Groovy Console starts, edit the groovy-starter.conf file as suggested by Squelsh.
回答3:
You can write an external Groovy script that does all the imports, creates a GroovyConsole object, and calls the run() method on this object.
See also http://groovy.codehaus.org/Groovy+Console#GroovyConsole-EmbeddingtheConsole
For example: start.groovy
import groovy.ui.Console;
import com.botkop.service.*
import com.botkop.service.groovy.*
def env = System.getenv()
def service = new ServiceWrapper(
userName:env.userName,
password:env.password,
host:env.host,
port:new Integer(env.port))
service.connect()
Console console = new Console()
console.setVariable("service", service)
console.run()
From a shell script call the groovy executable providing it with the groovy script:
#!/bin/bash
if [ $# -ne 4 ]
then
echo "usage: $0 userName password host port"
exit 10
fi
export userName=$1
export password=$2
export host=$3
export port=$4
export PATH=~/apps/groovy/bin:/usr/bin:$PATH
export CLASSPATH=$(find lib -name '*.jar' | tr '\n' ':')
groovy start.groovy
The code in GroovyConsole can now make use of the imports done in start.groovy, as well as of the variables created and passed with the setVariable method ('service' in the example).
回答4:
At least on Linux groovy GroovyConsole is a Script has the Following command:
startGroovy groovy.ui.Console "$@"
startGroovy itself is a script which starts Java. Within the startGroovy script you should be able to modify your classpath and add the missing librarys.
From startGroovy:
startGroovy ( ) {
CLASS=$1
shift
# Start the Profiler or the JVM
if $useprofiler ; then
runProfiler
else
exec "$JAVACMD" $JAVA_OPTS \
-classpath "$STARTER_CLASSPATH" \
-Dscript.name="$SCRIPT_PATH" \
-Dprogram.name="$PROGNAME" \
-Dgroovy.starter.conf="$GROOVY_CONF" \
-Dgroovy.home="$GROOVY_HOME" \
-Dtools.jar="$TOOLS_JAR" \
$STARTER_MAIN_CLASS \
--main $CLASS \
--conf "$GROOVY_CONF" \
--classpath "$CP" \
"$@"
fi
来源:https://stackoverflow.com/questions/821327/how-do-you-configure-groovyconsole-so-i-dont-have-to-import-libraries-at-startu