Running an ANT task

ANT is a popular build automation tool that provides a great degree of flexibility. It also provides tasks, such as echo and touch, that are not available in Maven. There might be advantages in combining ANT tasks with Maven to achieve certain goals, though it is best to avoid it until it's inevitable.

Maven provides a mechanism to run arbitrary ANT tasks by way of the Maven AntRun plugin. Let us see how to use this to run an ANT task in our project.

How to do it...

  1. Open a project for which you want to run ANT tasks (project-with-ant).
  2. Add the following plugin configuration to the pom file:
         <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
              <execution>
                <phase>package</phase>
                <configuration>
                  <target>
                      <echo message="Calling ant task in package phase"/>
                  </target>
                </configuration>
                <goals>
                  <goal>run</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
  3. Run the following Maven command:
    mvn clean package
    
  4. Observe the output:
    How to do it...

How it works...

We configured the Maven AntRun plugin to run an ANT target during the package phase. In the ANT target, we specified a simple echo task, which outputted a string we wanted.

Instead of the echo task, we could write more complex tasks. The Maven AntRun plugin also provides a means for ANT tasks to refer to Maven properties, class paths, and others.

There's more...

It is good practice to separate ANT tasks to a separate ANT build script (build.xml) and invoke the same from Maven. Let us see how to do this:

  1. Create a simple ANT build script, build.xml, and add the following contents:
      <project name="project-with-ant" default="echo" basedir=".">
        <description>
            Simple ant task to echo a string
        </description>
    
        <target name="echo">
            <echo message="Hello World"/>
       </target>
    </project> 
  2. Replace the target configuration in the pom file as follows:
    <target>
        <ant target="echo"/>
     </target>
  3. Run the Maven command:
    mvn clean package
    
  4. Observe the output:
    There's more...

The result is the same, but now the ANT scripts are separated from Maven.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.213.44