Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I auto load a database jar in Groovy without using the -cp switch?

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:

groovy RunScript.groovy

instead of:

groovy -cp ojdbc5.jar RunScript.groovy
like image 720
Joshua Avatar asked Oct 31 '08 18:10

Joshua


4 Answers

Summarized from Groovy Recipes, by Scott Davis, Automatically Including JARs in the ./groovy/lib Directory:

  1. Create .groovy/lib in your login directory
  2. Uncomment the following line in ${GROOVY_HOME}/conf/groovy-starter.conf

    load !{user.home}/.groovy/lib/*.jar

  3. Copy the jars you want included to .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.

like image 161
Ken Gentle Avatar answered Oct 11 '22 15:10

Ken Gentle


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:

this.class.classLoader.rootLoader.addURL(new URL("file:///path to file"))
like image 20
Joey Gibson Avatar answered Oct 11 '22 13:10

Joey Gibson


One way would be using @Grab in the code:

    @GrabConfig(systemClassLoader=true)
    @Grab('com.oracle:ojdbc6:12.1.0.2.0')
    Class.forName("oracle.jdbc.OracleDriver").newInstance()
like image 45
Cristi B. Avatar answered Oct 11 '22 14:10

Cristi B.


groovy is 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.

like image 21
mipadi Avatar answered Oct 11 '22 14:10

mipadi