scravy scravy - 4 months ago 8
Java Question

Insert custom build code / invoke java programm with Maven during build

I am having a project where there is code being generated by a third-party tool (typically invoked from the command line). I would like to align this tool with our maven build setup, i.e. I would like to have it invoked, for example before

maven compile
.

Is there a way to execute an arbitrary Java program using one of the numerous maven plugins? Where would I insert it in the POM?

Answer

You want to use the Exec Maven Plugin, using its exec goal, which lets you execute an external application.

About when the external application is going to be executed, you have to consider the default Maven Build Lifecycle. When you launch the build process, Maven executes the following (strictly ordered) phases:

  1. validate
  2. compile
  3. test
  4. package
  5. integration-test
  6. verify
  7. install
  8. deploy

You can decide at which of the steps above running the external application by configuring the phase element in the Exec Maven Plugin executions element:

<!-- Begin of POM -->
<project>
    ...
    <build>
        <plugins>
            <!-- Begin of Exec Maven Plugin -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <phase>validate</phase> <!-- Here, for example, validate -->
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>...</configuration>
            </plugin>
            <!-- Begin of Exec Maven Plugin -->
        </plugins>
    </build>
    ...
</project>
<!-- End of POM -->