17

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
Opal
  • 81,889
  • 28
  • 189
  • 210
Joshua
  • 26,234
  • 22
  • 77
  • 106

5 Answers5

17

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.

Ken Gentle
  • 13,277
  • 2
  • 41
  • 49
  • Not sure if this would be preferred though. There are times when I would rather use the "default classloader" of java. In that case I can put jars into jre/lib/ext to get autoloaded to the default classloader. – djangofan Oct 30 '11 at 00:43
5

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"))
user987339
  • 10,519
  • 8
  • 40
  • 45
Joey Gibson
  • 7,104
  • 1
  • 20
  • 14
  • Loading the JAR dynamically doesn't work for me unless I also instantiate any classes within the JAR dynamically as well. For example, if MyClass is in the JAR, I have to construct it like this: def myObj = Class.forName("com.whatever.MyClass").newInstance() Thus, it's way better just to include the JAR file somewhere within the groovy-starter.conf directories, unless there's a way around this that I don't know about. – seansand Apr 30 '10 at 16:06
2

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()
Cristi B.
  • 651
  • 7
  • 17
1

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.

mipadi
  • 398,885
  • 90
  • 523
  • 479
1

You could add the following shebang to the first line of your Groovy script:

#!/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
bonh
  • 2,863
  • 2
  • 33
  • 37
  • 1
    he's saying that he wants to simplify the script NOT moving the command parameter within groovy – Mache Aug 05 '20 at 11:04