Last Updated: October 01, 2018
·
283
· Dave Watts

Sidestepping the horror of code generation in Maven with Groovy

From https://area-51.blog/2009/11/07/using-groovy-to-generate-java-sources-in-maven/

Add the following to your pom.xml

<project>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-groovy-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/groovy</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.groovy.maven</groupId>
<artifactId>gmaven-plugin</artifactId>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<scriptpath>
<element>${basedir}/src/main/script</element>
</scriptpath>
<source>
// The code required to start the class file defined goes here
MyCodeGenerator mcg = new MyCodeGenerator()
mcg .generate( project )
</source>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<build>
<project>

Then in ${basedir}/src/main/script, create MyCodeGenerator.groovy

class MyCodeGenerator{
static generate( project ) {
// Do your stuff here
}
}