October 27, 2017

Groovy Goodness: Download Grab Dependencies In IntelliJ IDEA

In our Groovy scripts we can use the @Grab annotation. With this annotation we define dependencies for our script and they will be automatically downloaded and added to the class path when we run our script. When we use IntelliJ IDEA we can use a nice intention that is part of the IntelliJ IDEA Groovy support to download the dependencies from our IDE editor. IDEA downloads the dependencies and add it to the project module dependencies. This is useful, because this will also adds code completion for the classes in the dependency to our editor.

Let's see this with a little example. We have the following Groovy script in our Groovy project in IntelliJ IDEA:

We place the cursor on the @Grab annotation and enable the intention popup using Alt+Enter (check Keymap Reference for the key combination). We select the option from the popup:

IntelliJ IDEA downloads the dependency. When we look at our Project Structure and at the Module Dependencies we see the downloaded dependency:

In our example we added the Groovy script to a Groovy project in IntelliJ IDEA. When the project is a Gradle or Maven project we must make sure Ivy is part of the compile class path, because otherwise IntelliJ IDEA cannot download the dependencies using this intention. For example we could add to a Gradle build file the following dependency compileOnly 'org.apache.ivy:ivy:2.4.0'.

Written with Groovy 2.4.12 and IntelliJ IDEA 2017.2.5