Dark theme | Light theme

September 26, 2009

Groovy Goodness: Grab That Dependency

In Groovy scripts we can automatically download dependencies with Grape. Grape can be used as annotation (for a method or parameter) or with a plain method call. Apacy Ivy is used by Grape to find and download the dependencies. This means we can also use all Maven2 dependency repositories. If we want to add new repositories we must create a file ~/.groovy/grapeConfig.xml which is an Ivy configuration file and in it we can add a new repository. The downloaded files are saved in ~/.groovy/grapes.

The command-line grape command can be used to download dependencies or to list the already downloaded dependencies. For example with $ grape list we get a list of all dependencies on our local computer.

import org.apache.commons.lang.SystemUtils

@Grab(group='commons-lang', module='commons-lang', version='2.4')
def printInfo() {
    if (SystemUtils.isJavaVersionAtLeast(5)) {
        println 'We are ready to use annotations in our Groovy code.'
    } else {
        println 'We cannot use annotations in our Groovy code.'


Default Grape configuration file:

  <settings defaultResolver="downloadGrapes"/>
    <chain name="downloadGrapes">
      <filesystem name="cachedGrapes">
        <ivy pattern="${user.home}/.groovy/grapes/[organisation]/[module]/ivy-[revision].xml"/>
        <artifact pattern="${user.home}/.groovy/grapes/[organisation]/[module]/[type]s/[artifact]-[revision](-[classifier]).[ext]"/>
      <!-- todo add 'endorsed groovy extensions' resolver here -->
      <ibiblio name="codehaus" root="" m2compatible="true"/>
      <ibiblio name="ibiblio" m2compatible="true"/>
      <ibiblio name="java.net2" root="" m2compatible="true"/>