java 如何在不使用 -cp 开关的情况下在 Groovy 中自动加载数据库 jar?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/254385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I auto load a database jar in Groovy without using the -cp switch?
提问by Joshua
I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:
我想简化调用 Oracle 数据库的 Groovy 脚本的执行。如何将 ojdbc jar 添加到默认类路径以便我可以运行:
groovy RunScript.groovy
instead of:
代替:
groovy -cp ojdbc5.jar RunScript.groovy
采纳答案by Ken Gentle
Summarized from Groovy Recipes, by Scott Davis, Automatically Including JARs in the ./groovy/lib Directory:
总结自Groovy Recipes,作者 Scott Davis,自动将 JAR 包含在 ./groovy/lib 目录中:
- Create
.groovy/libin your login directory Uncomment the following line in ${GROOVY_HOME}/conf/groovy-starter.conf
load !{user.home}/.groovy/lib/*.jarCopy the jars you want included to
.groovy/lib
.groovy/lib在您的登录目录中创建取消注释 ${GROOVY_HOME}/conf/groovy-starter.conf 中的以下行
load !{user.home}/.groovy/lib/*.jar将您想要包含的 jars 复制到
.groovy/lib
It appears that for Groovy 1.5 or later you get this by default (no need to edit the conf), just drop the jars in the /lib dir.
似乎对于 Groovy 1.5 或更高版本,默认情况下您会得到它(无需编辑 conf),只需将 jar 放在 /lib 目录中即可。
回答by Joey Gibson
There are a few ways to do it. You can add the jar to your system's CLASSPATH variable. You can create a directory called .groovy/lib in your home directory and put the jar in there. It will be automatically added to your classpath at runtime. Or, you can do it in code:
有几种方法可以做到。您可以将 jar 添加到系统的 CLASSPATH 变量中。您可以在您的主目录中创建一个名为 .groovy/lib 的目录并将 jar 放在那里。它将在运行时自动添加到您的类路径中。或者,您可以在代码中执行此操作:
this.class.classLoader.rootLoader.addURL(new URL("file:///path to file"))
回答by bonh
You could add the following shebangto the first line of your Groovy script:
您可以将以下shebang添加到 Groovy 脚本的第一行:
#!/usr/bin/env groovy -cp ojdbc5.jar
Then, mark the script executable:
然后,标记脚本可执行文件:
chmod u+x RunScript.groovy
Now, running the script by itself will set the classpath automatically.
现在,单独运行脚本将自动设置类路径。
./RunScript.groovy
回答by Cristi B.
One way would be using @Grab in the code:
一种方法是在代码中使用@Grab:
@GrabConfig(systemClassLoader=true)
@Grab('com.oracle:ojdbc6:12.1.0.2.0')
Class.forName("oracle.jdbc.OracleDriver").newInstance()
回答by mipadi
groovyis just a wrapper script for the Groovy JAR that sets up the Java classpath. You could modify that script to add the path to your own JAR, as well, I suppose.
groovy只是用于设置 Java 类路径的 Groovy JAR 的包装器脚本。我想您也可以修改该脚本以将路径添加到您自己的 JAR 中。

