Creating a Simple Maven Plugin

After such a long time!

In this tutorial we will learn about how to create our own Maven plugin. We can later even use that plugin while executing some lifecycle steps for our other Maven projects.
We will learn a example here, which actually prints Hello world. So, when we execute this plugin while executing Compile for some other maven project, in console we should get output - Hello world.

So let's start.

Well we can divide this tutorial in 2 parts.

1. How to create a Maven Plugin.
2. How to use this plugin in some other Maven application.

1. How to create Maven Plugin.

Step1. Create a new Maven Project using Mojo Archetypes.

Step 2: Provide some required details in this step.

Group Id : com.helloworld.plugin
Artifact Id : com.helloworld.plugin

Note: Package field will be automatically generated.

Then, click on Finish.

Step 3: The project is generated now. Now, what we need to do is, add some plugins and dependencies in pom.xml.


Step 4: Now, we will create a simple Java Class which will show us Greetings!! Hello World!

In this step we will also define that the name of the goal will be say-helloworld and this plugin will be executes while executing the lifecycle phase COMPILE.

package com.helloworld.sample;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;

@Mojo(name = "say-helloworld",defaultPhase = LifecyclePhase.COMPILE)
public class HelloWorld extends AbstractMojo{

    public void execute() throws MojoExecutionException, MojoFailureException 
        getLog().info("Hello World!!");

Step 5: This plugin is now ready to run. Just install it  by doing the following -

Right click on the project -> Run As -> Install

2. How to use the plugin.

Step 1: Create a simple java project.

      File -> New -> Java Project

Step 2: Convert this Project in Maven Project (For more information regarding maven , please check this link)

      Right click on the project -> Configure  -> Convert to Maven Project.

Step 3:  Add the following piece of code to the pom.xml of the project to add the above plugin to it.


Step 4:  Now, run mvn package on that project

You will find the output Hello World!! in the output

Happy Learning!