Run Ant from Maven

You may have one of these needs:

  • You or your team have to use Ant but you are have Maven and do not want everyone to config Ant on their local computer.
  • You want to just ‘mvn install’ and let Maven does Ant tasks.

Then this page is for you.

Full Code:

2_maven_with_ant.zip

What you need to run this:

  • Maven 3

Explain:

Our goal is that we want to run ‘mvn install’ and Maven will run a target in an Ant build file (build.xml)

Assume that you have the Ant build file, build.xml, look like this:

<project name="mavn_with_ant_example" basedir=".">
    <target name="install">
	<echo message="Hello from ANT" />
    </target>
</project>

It will just print “Hello from ANT” to console.

To hook our Ant build with ‘mvn install’, you need to add Ant plugin in pom.xml

<build>
        <plugins>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                   <execution>
                        <id>install_all</id>
                        <phase>install</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <ant antfile="build.xml"
                                     target="install"/>
                            </tasks>
                        </configuration>
                    </execution> 
                </executions>
            </plugin>
        </plugins>
    </build>

What does these codes do?

These lines,

<phase>install</phase>
<goals>
   <goal>run</goal>
</goals>

Basically, it just hooks ant to maven goal. It means that “when the run goal of the install phase is running, run my antrun plugin” In the other words, when you run ‘mvn install’ it will run this antrun plugin.

Then this line:

<configuration>
   <tasks>
      <ant antfile="build.xml" target="install"/>
   </tasks>
</configuration>

It means that the antrun plugin will run the install target in build.xml . Do not be confused the install target with ‘mvn install’ , they are not related.

After this, you can just try to run this command in your console:

mvn install

Then you will see this:

main:

install:
     [echo] Hello from ANT
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.391 s
[INFO] Finished at: 2017-12-09T14:41:54+01:00
[INFO] Final Memory: 14M/155M
[INFO] ------------------------------------------------------------------------

See the line number 4 there.