comment 1

Maven 3 Plugin Development

Hi,

i was needed to write a maven plugin for one of our products. The product had four or five maven plugins to assemble a final WAR file, and it was very complicated to create one. My plugin’s task was tidying this mess up. So, i started to learn mojos,

Mojo shortly means maven pojos. And since maven 3 we can easily write a mojo with annotations (came with Java 5).  Before maven 3 writing mojos was lethal, because mojo structure was built on java-docs. Therefore annotations came and we are saved.

Here’s the requirements of writing a maven 3 plugin:

  1. First, our mojo should be placed in a maven project. Create a classic maven project, for a fast setup you can use below archetype, but i recommend you to follow my steps to understand development fully.
  2. Addind below dependency to use annotations.
  3. Adding below dependency to get maven variables such as ${project}
  4. Making project packaging to:
  5. Adding below dependency to execute other Mojos (maven plugins) from your plugin. (This is optional, and was my requirement for my module.)
  6. Adding below plugin to override maven’s default-descriptor execution to process-classes. This is required.

Now everything is ready to write a mojo. As i told, we need to annotate our class with @Mojo and extend it from AbstractMojo. 

The properties of @Mojo annotations are described below:

  • name – your plugin’s goal, you will write it into <execution><goals><goal> tag
  • threadSafe – maven 3 supports parallel builds, with setting this property true, you make maven run this plugin synchronized.
  • defaultPhase – this is the default phase of your plugin, it can be overriden by the plugin user.
  • requiresDependencyResolution – it’s your plugins dependency coverage section. TEST means you can access all dependencies.

The other properties and the details can be found here.

The next thing that we should do is overriding execute function of AbstractMojo.

You can access all project properties by adding below dependency into your @Mojo class.

Here’s an example:

 @Parameter annotation lets you to define maven parameters. With defaultValue property we are accessing a maven property, and setting it readonly to be sure noone can overwrite it.

For last i want to show how to execute a maven plugin in your plugin code.

mavenSession and pluginManager variables are :

@Component annotation is for configuring injection of Plexus components or Maven context components.

And at the end here’s an example usage of your plugin:

 

Thanks !

1 Comment so far

Leave a Reply

Your email address will not be published. Required fields are marked *