How do I include jars in a groovy script? [duplicate]

ε祈祈猫儿з 提交于 2019-12-28 07:39:27

问题


I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.


回答1:


If you really have to you can also load a JAR at runtime with:

this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())



回答2:


Starting a groovy script with #!/usr/bin/env groovy has a very important limitation - No additional arguments can be added. No classpath can be configured, no running groovy with defines or in debug. This is not a groovy issue, but a limitation in how the shebang (#!) works - all additional arguments are treated as single argument so #!/usr/bin/env groovy -d is telling /usr/bin/env to run the command groovy -d rathen then groovy with an argument of d.

There is a workaround for the issue, which involves bootstrapping groovy with bash in the groovy script.

#!/bin/bash                                                                                                                                                                 
//usr/bin/env groovy  -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@; exit $?

import org.springframework.class.from.jar
//other groovy code
println 'Hello'

All the magic happens in the first two lines. The first line tells us that this is a bash script. bash starts running and sees the first line. In bash # is for comments and // is collapsed to / which is the root directory. So bash will run /usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@ which starts groovy with all our desired arguments. The "$0" is the path to our script, and $@ are the arguments. Now groovy runs and it ignores the first two lines and sees our groovy script and then exits back to bash. bash then exits (exit $?1) with status code from groovy.




回答3:


My Favorite way to do this is with Groovy Grapes. These access the Maven Central Repository, download the referenced jar, and then put it on the classpath. Then you can use the library like any other library. The syntax is really simple:

@Grab(group='com.google.collections', module='google-collections', version='1.0')

You can read more details here. One major advantage here is that you don't need to distribute your dependencies when you distribute your script. The only drawback to this method is that the Jar has to be in the Maven repository.




回答4:


You can add the jars to $HOME/.groovy/lib




回答5:


You can also try out Groovy Grape. It lets you use annotations to modify the classpath. Its experimental right now, but pretty cool. See docs.groovy-lang.org/.../grape




回答6:


The same as you would in Java.

This is an example of running a MySQL status monitoring script. mysql.jar contains the MySQL connector that I call from script status.groovy.

groovy -cp mysql.jar status.groovy ct1




回答7:


Below is a combination of Patrick's solution, Maarteen Boekhold's solution, and foozbar's comment that works with both Linux and Cygwin:

#!/bin/bash
// 2>/dev/null; SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
// 2>/dev/null; OPTS="-cp $SCRIPT_DIR/lib/extra.jar:$SCRIPT_DIR/lib/spring.jar"
// 2>/dev/null; OPTS="$OPTS -d"
// 2>/dev/null; OPTS="$OPTS -Dlog4j.configuration=file:/etc/myapp/log4j.xml"
// 2>/dev/null; exec groovy $OPTS "$0" "$@"; exit $?

import org.springframework.class.from.jar
//other groovy code
println 'Hello'

How it works:

  • // is a valid groovy comment, so all of the bash commands are ignored by Groovy.
  • // will return an error, but the error output is redirected to /dev/null and is therefore not displayed.
  • bash executes commands following a semicolon even though the previous command failed.
  • exec replaces the current program in the current process without forking a new process. Thus, groovy runs within the original script process (ps shows the process as the script rather than the groovy executable)
  • The exit $? statement following exec groovy prevents bash from trying to interpret the rest of the script as a bash script, and also preserves the return code from the groovy script.

The above bash trick is more convenient in some cases than the RootLoader trick because you can use regular import statements within the script. Using the RootLoader trick forces you to load all of the classes using reflection. This is fine in some situations (such as when you need to load a JDBC driver), but inconvenient in others.

If you know your script will never be executed on Cygwin, then using Patrick's or Maarteen's solution will likely result in slightly better performance because they avoid the overhead of generating and throwing away an error.




回答8:


Adding to @Patrick his answer, which helped me a lot, I recently discovered another trick.

If you add lots of jars to the classpath all on one line, things can become quite unreadable. But you can do the following!

#!/bin/bash
//bin/true && OPTS="-cp blah.jar -Dmyopt=value"
//bin/true && OPTS="$OPTS -Dmoreopts=value2"
//usr/bin/env groovy $OPTS "$0" $@; exit $?

println "inside my groovy script"

Let your imagination run wild on how complex a command line you can break down this way into manageable pieces

Maarten




回答9:


If you want to use it right away before the import declarations it is possible like this :) :

// printEmployees.groovy
this.class.classLoader.rootLoader.addURL(
   new URL("file:///C:/app/Dustin/product/11.1.0/db_1/jdbc/lib/ojdbc6.jar"))
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:orcl", "hr", "hr",
                      "oracle.jdbc.pool.OracleDataSource")
sql.eachRow("SELECT employee_id, last_name, first_name FROM employees")
{
   println "The employee's name is ${it.first_name} ${it.last_name}."
}

Taken from this javaworld.com article.



来源:https://stackoverflow.com/questions/306139/how-do-i-include-jars-in-a-groovy-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!