Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Build Tools and Ecosystem

Grape and Dependency Management in Groovy Scripts

Use libraries from Groovy scripts without a build file: @Grab, @GrabResolver, @GrabExclude, the local Ivy cache, Maven coordinates, and when to switch to Gradle.

One of Groovy's best habits is that a single .groovy file can be a complete program. Need an HTTP client, a CSV parser or a database driver? You do not have to create a project. The Grape dependency manager lets the script say what it needs, and Groovy downloads the jars the first time the script runs.

Groovy and the network cannot be used on this site, so the Groovy code is read-only. The Java stand-ins demonstrate how a coordinate string is parsed and how a local cache avoids repeated downloads.

@Grab

GROOVY
@Grab('org.apache.commons:commons-lang3:3.14.0')
import org.apache.commons.lang3.StringUtils

println StringUtils.capitalize("groovy")
println StringUtils.reverse("abc")

The annotation is placed on an import (or on a class or method). Running groovy script.groovy resolves the coordinates group:module:version, downloads the jar and its dependencies into the local cache, adds them to the classpath, and then executes the script. The first run needs network access; later runs use the cache.

Longer forms use named arguments:

GROOVY
@Grab(group = 'com.google.code.gson', module = 'gson', version = '2.11.0')
import com.google.gson.Gson

println new Gson().toJson([a: 1, b: [2, 3]])

You can grab several at once with @Grapes:

GROOVY
@Grapes([
  @Grab('org.apache.commons:commons-csv:1.10.0'),
  @Grab('org.slf4j:slf4j-simple:2.0.13')
])
import org.apache.commons.csv.CSVFormat

Controlling resolution

  • @GrabResolver adds a repository: @GrabResolver(name='mine', root='https://repo.example.com/maven').
  • @GrabExclude drops a transitive dependency: @GrabExclude('commons-logging:commons-logging').
  • @GrabConfig(systemClassLoader=true) is needed by some libraries that load themselves with the system class loader, such as JDBC drivers:
GROOVY
@GrabConfig(systemClassLoader = true)
@Grab('com.h2database:h2:2.2.224')
import groovy.sql.Sql

def sql = Sql.newInstance('jdbc:h2:mem:demo', 'sa', '', 'org.h2.Driver')
sql.execute 'create table t(id int)'

Version ranges and latest are accepted (version='[3.0,4.0)', '+'), but they make runs unrepeatable. Pin exact versions.

Where the jars go

Grape uses Apache Ivy. By default jars are stored in ~/.groovy/grapes and the Ivy settings can be changed with ~/.groovy/grapeConfig.xml. Useful commands:

TEXT
grape install org.apache.commons commons-lang3 3.14.0    # download without running anything
grape list                                                 # show what is cached
grape resolve org.apache.commons commons-lang3 3.14.0     # print the resolved jar paths

A good habit for build servers: run grape install while network access is available, then run scripts offline.

Grape in a larger context

Situation Choose
One-off script, quick tool Grape
Shared project with tests Gradle or Maven
Reproducible build with checksums Gradle with dependency locking
Corporate network with a proxy Grape with grapeConfig.xml pointing at your repository
Jenkins pipeline libraries @Library and @Grab limited by the sandbox

Grape is convenient, but it has limits: no dependency locking, no checksum verification beyond what Ivy checks by default, and slower startup the first time. As soon as a script grows into a project, move to a proper build tool (see Gradle build scripts).

Security notes

  1. A @Grab runs code from a downloaded jar with the script's permissions. Only use trusted repositories, and pin versions.
  2. Do not run scripts from strangers that contain @Grab; they can fetch and execute anything.
  3. Prefer HTTPS repositories, and mirror dependencies internally for production work.

Try it: parsing coordinates (stand-in)

A Maven coordinate is a group:module:version string. This Java program parses the short and the extended forms the way a dependency manager must.

Java Stand-in: parse dependency coordinates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: a cache that downloads once (stand-in)

The first call "downloads", later calls hit the cache, just like the second run of a script.

Java Stand-in: local jar cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @Grab do?

    Grape resolves the coordinates, caches the jars locally and puts them on the classpath.
  2. 2. Which annotation removes an unwanted transitive dependency?

    @GrabExclude names a group:module pair to leave out.
  3. 3. Why pin exact versions in @Grab?

    A range may resolve to a different jar tomorrow, which breaks repeatability.
  4. 4. When should a script move from Grape to Gradle or Maven?

    Grape suits small scripts. Larger projects need locking, tasks, testing support and reproducible builds.

Summary

  • @Grab('group:module:version') makes a single script self-contained.
  • @GrabResolver, @GrabExclude and @GrabConfig control repositories, exclusions and class loading.
  • Jars are cached in ~/.groovy/grapes, and grape install can pre-fill the cache.
  • Pin versions, use trusted HTTPS repositories, and switch to a build tool as the script grows.

Next: Groovy with Java and Spring