Programmer's Cookbook

Recipes for the practical programmer

Monday, October 01, 2007

 

Creating a Maven 2 Plugin (Mojo)

Creating a new plugin (a.k.a. Mojo) is really dead simple, although the Maven site seems to make it complicated.

Start by running Maven at the command line to create a new plugin project.


mvn archetype:create \
-DgroupId=com.blogspot.progcookbook.mojo \
-DartifactId=maven-coolass-plugin \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-mojo


The groupId will typically be the same for all of your plugins. I like to use my reverse domain name followed by ".mojo". The artifactId naming is very important. Besure to use the format "maven-<PLUGIN_NAME>-plugin".

The plugin name is used to execute individual goals. So if my plugin is named "coolass" and the goal is "runit", then I would type "mvn coolass:runit" at the command line to execute the goal.

After you run the command above, it will create a sample project with one class called MyMojo.java. Rename it as needed and make a copy for each "goal" supported by your plugin.

The goal name will need to be defined in XDoclet style tags just above the class name in the file. Here is the class definition in the sample MyMojo.java file.


/**
* Goal which touches a timestamp file.
*
* @goal touch
*
* @phase process-sources
*/
public class MyMojo


Here the goal is "touch", so the way this works is that running "mvn coolass:touch" will run the execute() method in this class. Rename the goal as needed.

In the sample file you will see a single member variable named outputDirectory. Note the XDoclet style annotation above it.


/**
* Location of the file.
* @parameter expression="${project.build.directory}"
* @required
*/
private File outputDirectory;


The @parameter annotation makes this configurable in the pom.xml, and the expression defines the default value. Add and remove parameters as needed, using @required when you want to force the issue.

The last step is to install your new plugin in your local repository.


mvn install


There are more details, but this is enough to get you up and running. Check out the Maven Plugin Dev Center for more details.

Labels: ,


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?