August 22, 2009

Grassroots Groovy: the Maven Route (part 1)

We can introduce Groovy into our projects at grassroots level. In a series of blog posts we learn different routes we can follow to get our Java projects more Groovy. First off we look at how we can add Groovy sources to our Maven based Java project. But we will also see how XML handling, unit testing, Spring integration and other routes allow us to add Groovyness to a Java project in other posts.

The GMaven plugin adds Groovy support to a Maven based Java project. We configure the plugin to allow Groovy classes to be compiled just like normal Java classes. The compiled Groovy classes can than be integrated with the Java classes.

Let's start with the Maven quickstart archetype to create a simple Java Maven project:

$ mvn archetype:generate -DgroupId=com.mrhaki.sample -DartifactId=sample-app -DinteractiveMode=false
$ cd sample-app

Maven creates a new directory sample-app with a basic Java application at src/main/java/com/mrhaki/sample/App.java. We open pom.xml to add the GMaven plugin so we can compile and use our Groovy code:

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
            <!-- GMaven plugin so we can compile Groovy sources. -->
        <!-- Extra dependency for Groovy libraries for runtime. -->

Now our Groovy sources ending with .groovy in the directory src/main/groovy are compiled into target/classes and Groovy sources in the directory src/test/groovy are compiled into the target/test-classes directory when we run mvn install. We create a Groovy source file at src/main/groovy/com/mrhaki/sample/MyGroovy.groovy:

package com.mrhaki.sample

class MyGroovy {

    String username
    def reverseName() {
    def calculateBigDecimals() {
        40G + 2G

For this example we add a new test method to the existing AppTest class in the directory src/test/java/com/mrhaki/sample. In this test method we create an instance of the Groovy class and invoke the methods to test them:

public void testGroovy() {
    MyGroovy groovy = new MyGroovy();
    assertEquals("mrhaki", groovy.getUsername());
    assertEquals("ikahrm", groovy.reverseName());
    assertEquals(new java.math.BigInteger("42"), groovy.calculateBigDecimals());

Now we run $ mvn test and our Groovy class is compiled and the Java test class will be executed without errors. So we see integrating Groovy with Java is not that difficult when we already have a Maven based Java project. In a following post we learn how we can use Groovy in the Maven POM as another route to get Groovy into our Java project.