August 29, 2009

Create new Maven Plugin

« Spring Quartz Example | Main | Spring Mail Example »

The creation of new Maven plugins is easy and straight forward. The basic class of Maven plugins is the Mojo class. This class is extended from AbstractMojo. The execute() method of the Mojo class is being executing during the Maven build process. Configuration parameters will be injected directly to the members of the Mojo class.

The following example describes the steps of how to create a Maven plugin:
First Step - create Maven plugin artifact:

mvn archetype:create -DgroupId=org.developers.blog -DartifactId=maven-hello-world-plugin -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-mojo
Second Step - Implement your Mojo
package org.developers.blog;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;

import java.io.File;

/**
 * Goal which touches a timestamp file.
 *
 * @goal sayHello
 * 
 * @phase process-sources
 */
public class HelloWorldMojo extends AbstractMojo {
    /**
     * add standard maven environment parameters
     * @parameter expression="${project.build.directory}"
     * @required
     */
    private File outputDirectory;

    /**
     * a paramter which will be injected from configuration/myName in pom.xml
     * @parameter
     * @required
     */
    private String myName;
    
    //the main logic method of your plugin
    public void execute() throws MojoExecutionException {
        getLog().info("Hello Mister " + myName);
    }
}
After that your build your project and configures it at another project pom.xml file.

Third Step - Usage of the Maven plugin
<build>
    <plugins>
        <plugin>
            <groupId>org.developers.blog</groupId>
            <artifactId>maven-hello-world-plugin</artifactId>
            <version>1.0-SNAPSHOT</version>
            <configuration>
                <myName>Rafael Sobek</myName>
            </configuration>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>sayHello</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
After that you can call the plugin with the following command.
mvn org.developers.blog:maven-hello-world-plugin:1.0-SNAPSHOT:sayHello
The result:
[INFO] [hello-world:sayHello]
[INFO] Hello Mister Rafael Sobek
The full example you can download here.

Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 2:43 PM in Maven

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« August »
SunMonTueWedThuFriSat
      1
2345678
9101112131415
16171819202122
23242526272829
3031