I love Maven for its flexibility, but this flexibility at times makes it hard to figure out how to achieve certain tasks. In my case I wanted to execute a certain Java class that is included in the project at some point during the build lifecycle. While I can see many uses in my case the class itself compiles a SQL dump out of several source files so it can be included in the final artifact.

Integrating with Maven’s build lifecycle

Long story short, here is what you need to add to your pom.xml:

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>exec-maven-plugin</artifactId>
      <version>1.2</version>
      <executions>
        <execution>
          <id>build-dump</id>
          <phase>process-classes</phase>
          <goals>
            <goal>java</goal>
          </goals>
        </execution>
      </executions>
      <configuration>
        <mainClass>com.example.BuildDump</mainClass>
      </configuration>
    </plugin>
  </plugins>
</build>
 <pluginManagement>

The org.codehaus.mojo.exec-maven-plugin is used to execute the class com.example.BuildDump. The execution is done in the process-classes lifecycle using the java goal of the plugin. The id is arbitrary but has to be unique.

The whole idea of this snippet is to hook certain plugin’s goal into maven’s lifecycle at a certain phase. In that sense, the same effect can be achieved by calling (on the command line)

mvn exec:java -DmainClass=com.example.BuildDump

As you can see the goal in the execution of the pom.xml corresponds to the part after the colon, the part before the colon references the plugin (plugin:goal). If I recall correctly org.codehaus.mojo.*-maven-plugins have a shorthand name which is the part before -maven-plugin.

The execution doesn’t have to take place in the process-classes phase but it has to take place after the compile phase so the class has already been compiled. It also has to take place before the test phase if you need the files during testing. I do not know if the process-classes phase is correct (it is used to post-process the generated files from compilation, for example to do bytecode enhancement on Java classes.) but it fulfills these two requirements.