Adding Groovy Sources to Maven Build Path


Say you want to run a groovy class method from your Java project in Maven. You've placed the script file at src/main/groovy/script/MyGroovyScriptClass.groovy. In Java, you would load the class and execute its method like so:

final ClassLoader parent = this.getClass().getClassLoader();
final GroovyClassLoader loader = new GroovyClassLoader(parent);
URL url = this.getClass().getResource("/script/MyGroovyScriptClass.groovy");
try {
    final Class groovyClass = loader.parseClass(url.getFile());
    this.jdbcRouteCSV = (GroovyObject) groovyClass.newInstance();
    Object[] args = {};
    this.jdbcRouteCSV.invokeMethod("myGroovyScriptMethod", args);
}
catch (IllegalAccessException iaex){
    ...
}
catch (InstantiationException iex){
    ...
}

The problem is that this won't work in Maven, unless you add the groovy folder to your resource path.



Adding the following build element to your pom.xml will add groovy script/class files to your classpath.

In a multi module environment, this excerpt be placed in the module's pom.xml containing groovy resources. (This will likely be a child module)
If you need to add the groovy files as source files, then change <goal>add-resource</goal> to <goal>add-source</goal> and <phase>generate-resources</phase> to <phase>generate-sources</phase>
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>1.7</version>
            <executions>
                <execution>
                    <id>add-resource</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>add-resource</goal>
                    </goals>
                    <configuration>
                        <resources>
                            <resource>
                                <directory>src/main/groovy</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
                <execution>
                    <id>add-test-source</id>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>add-test-resource</goal>
                    </goals>
                    <configuration>
                        <resources>
                            <resource>
                                <directory>src/test/groovy</directory>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

See more about the plugin: build-helper-maven-plugin.

Comments

Popular posts from this blog

Atmosphere Websockets & Comet with Spring MVC

Microservices Tech Stack with Spring and Vert.X