Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 41 ยท Releasing and Production

Writing a Simple Maven Plugin

Write your own Maven plugin: the maven-plugin packaging, a Mojo class with @Mojo and @Parameter, the generated descriptor, phase binding and testing.

Almost everything Maven does is done by plugins, and writing one is less mysterious than it looks: a plugin is a jar with a few Java classes called Mojos and a descriptor that lists them. When you need a custom build step, such as generating a file, checking a project rule or printing a report, a small plugin is cleaner than a pile of shell scripts, and you can reuse it across projects.

This lesson walks through the pieces of a plugin: the project setup, the Mojo class with its annotations, the plugin descriptor that Maven reads, how a goal binds to a lifecycle phase, and how to test it. A plugin needs the real Maven runtime, so those parts are read-only here. The Java stand-ins reproduce the mechanics (annotations, descriptor generation, parameter injection, execution) so you can see what Maven does with your class.

Parts of a plugin

Mojo A Java class that implements one goal.
Annotations @Mojo names it; @Parameter configures it.
Descriptor plugin.xml generated at build time.
maven-plugin packaging Builds the plugin jar.
1 / 2

Setting up the project

A plugin is its own Maven project with a special packaging type. By convention the artifactId is <something>-maven-plugin (names of the form maven-<something>-plugin are reserved for the Apache Maven project). Maven derives the goal prefix from that name, so greeter-maven-plugin gets the prefix greeter.

XML
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>greeter-maven-plugin</artifactId>
  <version>1.0.0</version>
  <packaging>maven-plugin</packaging>

  <properties>
    <maven.compiler.release>17</maven.compiler.release>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>3.9.9</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.plugin-tools</groupId>
      <artifactId>maven-plugin-annotations</artifactId>
      <version>3.15.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>

Both dependencies use scope provided: Maven supplies those classes at runtime, so they must not be packaged into your plugin. Version numbers here are examples; use current releases. Building the project with the maven-plugin packaging also runs the maven-plugin-plugin, which creates the descriptor.

The Mojo class

A Mojo ("Maven plain Old Java Object", a pun on Pojo) extends AbstractMojo and implements execute(). Annotations from maven-plugin-annotations tell Maven the goal name, the default phase and the parameters:

Java
package com.example.greeter;

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

@Mojo(name = "greet", defaultPhase = LifecyclePhase.VALIDATE)
public class GreetMojo extends AbstractMojo {

    @Parameter(property = "greeter.name", defaultValue = "world")
    private String name;

    @Parameter(property = "greeter.times", defaultValue = "1")
    private int times;

    @Override
    public void execute() throws MojoExecutionException {
        if (times < 1) {
            throw new MojoExecutionException("times must be at least 1");
        }
        for (int i = 0; i < times; i++) {
            getLog().info("Hello, " + name + "!");
        }
    }
}

The @Mojo annotation gives the goal its name, greet. The @Parameter annotation turns a field into a configurable value with a default. Its property attribute lets users override it with -Dgreeter.name=Ada, and the same field can be configured in the POM. Mojos can also ask for Maven's own objects, such as the current project:

Java
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private org.apache.maven.project.MavenProject project;

Use getLog() rather than System.out, so messages follow Maven's logging levels and the -q/-X flags. Throw MojoExecutionException when something unexpected went wrong (an I/O error) and MojoFailureException when the build itself is judged a failure (a rule check did not pass). Both stop the build; the distinction affects the wording of the error report.

The plugin descriptor

Maven does not scan your classes at run time. It reads a generated file, META-INF/maven/plugin.xml, inside the plugin jar. The maven-plugin-plugin creates it during the process-classes phase by reading the annotations. It lists the plugin coordinates and prefix, and for every goal its name, class, default phase and parameters with their types, expressions and defaults.

XML
<mojo>
  <goal>greet</goal>
  <phase>validate</phase>
  <implementation>com.example.greeter.GreetMojo</implementation>
  <parameters>
    <parameter>
      <name>name</name>
      <type>java.lang.String</type>
    </parameter>
  </parameters>
  <configuration>
    <name implementation="java.lang.String" default-value="world">${greeter.name}</name>
  </configuration>
</mojo>

You never write this by hand. The command mvn plugin:descriptor regenerates it and mvn greeter:help (when the plugin includes the help goal, produced by maven-plugin-plugin's helpmojo) prints the goals and parameters in readable form.

Running and binding to a phase

After mvn install puts the plugin into the local repository (see repositories and the local cache), a goal can be invoked directly by full coordinates or, once the group is listed under pluginGroups in settings.xml, by prefix:

Terminal
mvn com.example:greeter-maven-plugin:1.0.0:greet -Dgreeter.name=Ada
mvn greeter:greet -Dgreeter.times=3

To make it part of every build, a consuming project binds the goal to a phase with an execution, exactly as plugins and goals describes:

XML
<build>
  <plugins>
    <plugin>
      <groupId>com.example</groupId>
      <artifactId>greeter-maven-plugin</artifactId>
      <version>1.0.0</version>
      <configuration>
        <name>team</name>
      </configuration>
      <executions>
        <execution>
          <phase>initialize</phase>
          <goals><goal>greet</goal></goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

The phase here overrides the Mojo's defaultPhase. When several goals share a phase, they run in the order of declaration in the POM.

Testing a plugin

Two levels of testing cover most needs. Unit tests call the Mojo directly: set the private fields (through reflection or by giving the class a package-private setter), call execute() and assert on behavior; a failure case checks that the expected exception is thrown. That is plain JUnit and runs in the normal test phase.

Integration tests run the plugin inside real Maven builds. The maven-invoker-plugin takes small sample projects from src/it/ (each a complete POM with a invoker.properties file), runs them with your freshly built plugin, and checks the build result and output with a verify script. This is how most Apache plugins are tested, because only a real build proves that the descriptor, defaults and phase binding all work.

Terminal
mvn verify -Prun-its

A Mojo-like simulator

The first stand-in is a tiny re-creation of the descriptor step. It defines its own @Mojo and @Parameter annotations, then uses reflection to read a class and print what a descriptor would contain. This is the same idea as maven-plugin-plugin, which reads annotations (or Javadoc tags) from your sources.

Java Generating a descriptor from annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Parameter injection and execution

The second stand-in plays the part of Maven when it runs a goal: it creates the Mojo, fills each field from the first available source (command line -D, then POM configuration, then the default), runs execute() and reports failure like a build would. The order of sources matches how real Maven resolves them.

Java Injecting parameters and running a goal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real and what is stand-in: the annotations, the parameter sources and the failure behavior mirror real Maven; the descriptor XML, the plugin classloader and the lifecycle are only modelled. In a real plugin you never write the reflection yourself, and you never see it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which packaging type does a Maven plugin project use?

    The maven-plugin packaging adds the plugin-plugin goals that generate the descriptor and bundle the plugin correctly.
  2. 2. What does @Parameter(property = "greeter.name") allow?

    The property attribute names the user property that can fill the field, in addition to configuration in the POM and the default value.
  3. 3. Which file does Maven read to learn the goals of a plugin?

    The generated plugin descriptor lists every goal, its default phase and its parameters, so Maven does not scan the classes at run time.
  4. 4. How do you stop the build from a Mojo?

    Maven reports the build as failed when execute() throws one of its two Mojo exceptions; System.exit would kill the whole Maven JVM.
  5. 5. Which tool runs sample projects against a freshly built plugin?

    The invoker plugin runs integration test projects from src/it with the plugin under test and verifies their results.

Summary

  • A plugin is a project with maven-plugin packaging, provided dependencies on the plugin API and annotations, and one Mojo class per goal.
  • @Mojo names the goal and default phase; @Parameter links fields to POM configuration, -D properties and defaults.
  • The maven-plugin-plugin generates META-INF/maven/plugin.xml, which Maven reads to find goals.
  • Consumers bind goals to phases with executions; use getLog() and Mojo exceptions to report results.
  • Test with plain unit tests for logic and maven-invoker-plugin for real builds.

Next, learn to defend your build against bad dependencies in Dependency Security and Supply Chain.