Maven Plugins
Maven plugins do all the real work in a Maven build. Maven itself only reads pom.xml and walks through the lifecycle; compiling, testing, packaging and running your code are all done by plugins and their goals.
This lesson explains how Maven plugins work, how to run a plugin goal, how to configure a plugin, how to bind a goal to a lifecycle phase, and how to use popular plugins such as Enforcer, Exec and Shade. It ends with a complete build that checks the JDK, runs the app and creates a single runnable JAR. If phases and pom.xml are new to you, read Maven in Java first.
What Are Maven Plugins and Goals?
A plugin is a JAR that contains one or more goals. A goal is a single task, such as "compile the main code" or "run the tests". You call a goal with the syntax prefix:goal.
| Plugin | Prefix | Main goals | Default phase |
|---|---|---|---|
maven-clean-plugin | clean | clean | clean |
maven-resources-plugin | resources | resources, testResources | process-resources |
maven-compiler-plugin | compiler | compile, testCompile | compile, test-compile |
maven-surefire-plugin | surefire | test | test |
maven-jar-plugin | jar | jar | package |
maven-install-plugin | install | install | install |
Ask Maven to describe a plugin and its goals:
mvn help:describe -Dplugin=compiler
Output (shortened):
Name: Apache Maven Compiler Plugin
Group Id: org.apache.maven.plugins
Artifact Id: maven-compiler-plugin
Version: 3.15.0
Goal Prefix: compiler
This plugin has 3 goals:
compiler:compile
Description: Compiles application sources.
compiler:help
Description: Display help information on maven-compiler-plugin.
compiler:testCompile
Description: Compiles application test sources.
How it works:
help:describeis itself a goal: thedescribegoal of the Maven Help plugin.- Maven maps the prefix
compilertoorg.apache.maven.plugins:maven-compiler-plugin, so you rarely type the full coordinates. - The version shown is the one your project uses. Pin it in
pluginManagement, as shown in Create a Maven Project, so every machine uses the same one.
Phases vs Goals: How Maven Plugins Run
When you run a phase, Maven runs every goal bound to that phase and to all phases before it. When you run a goal, Maven runs only that goal.
mvn package
Output (shortened):
[INFO] --- resources:3.4.0:resources (default-resources) @ greeter ---
[INFO] --- compiler:3.15.0:compile (default-compile) @ greeter ---
[INFO] --- resources:3.4.0:testResources (default-testResources) @ greeter ---
[INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ greeter ---
[INFO] --- surefire:3.5.6:test (default-test) @ greeter ---
[INFO] --- jar:3.5.0:jar (default-jar) @ greeter ---
[INFO] BUILD SUCCESS
Now run a single goal:
mvn compiler:compile
[INFO] --- compiler:3.15.0:compile (default-cli) @ greeter ---
[INFO] Nothing to compile - all classes are up to date.
[INFO] BUILD SUCCESS
How it works:
- Each log line reads
prefix:version:goal (execution-id) @ project. - The ids starting with
default-come from the lifecycle bindings Maven adds forjarpackaging. You did not declare these plugins; Maven bound them for you. - A goal run from the command line gets the execution id
default-cli. It skips everything else, socompiler:compilealone does not copy resources.
You can mix phases and goals in one command. They run left to right:
mvn clean package dependency:tree
Configure a Maven Plugin in pom.xml
Every goal has parameters. Set them inside <configuration> in the <plugin> element. This example makes the compiler report all warnings and treat them as errors.
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-Werror</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
package com.gocourse.greeter;
import java.util.ArrayList;
import java.util.List;
public class Greeter {
public static void main(String[] args) {
List names = new ArrayList(); // raw type: no <String>
names.add("Asha");
System.out.println("Hello, " + names.get(0));
}
}
mvn compile
Output (shortened):
[WARNING] /home/asha/greeter/src/main/java/com/gocourse/greeter/Greeter.java:[8,9] found raw type: java.util.List
[WARNING] /home/asha/greeter/src/main/java/com/gocourse/greeter/Greeter.java:[9,18] unchecked call to add(E) as a member of the raw type java.util.List
[ERROR] warnings found and -Werror specified
[INFO] BUILD FAILURE
Fix the code with List<String> names = new ArrayList<>(); and the build succeeds.
How it works:
<compilerArgs>passes extra options straight tojavac.-Xlint:allenables every warning and-Werrorturns them into errors.- A configuration placed directly under
<plugin>applies to every goal of that plugin, here bothcompileandtestCompile. - Plugins in the default group
org.apache.maven.pluginscan leave out<groupId>.
Note: Many parameters also have a user property you can set with
-Don the command line, such as-Dmaven.compiler.release=25or-DskipTests. Runmvn help:describe -Dplugin=compiler -Ddetailto list every parameter and its property.
Bind a Plugin Goal to a Lifecycle Phase With executions
Some plugins have no default binding. You attach their goals to a phase with an <execution>. The Maven Enforcer plugin is a good example: it checks build rules, such as the minimum JDK version, before anything is compiled.
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.6.3</version>
<executions>
<execution>
<id>check-build-environment</id>
<phase>validate</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireJavaVersion>
<version>[25,)</version>
</requireJavaVersion>
<requireMavenVersion>
<version>[3.9,)</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
Running mvn package with JDK 21 now stops at the first phase:
[INFO] --- enforcer:3.6.3:enforce (check-build-environment) @ greeter ---
[ERROR] Rule 0: org.apache.maven.enforcer.rules.version.RequireJavaVersion failed with message:
[ERROR] Detected JDK version 21.0.5 (JAVA_HOME=/usr/lib/jvm/java-21) is not in the allowed range [25,).
[INFO] BUILD FAILURE
With JDK 25, both rules pass and the build continues:
[INFO] --- enforcer:3.6.3:enforce (check-build-environment) @ greeter ---
[INFO] Rule 0: org.apache.maven.enforcer.rules.version.RequireJavaVersion passed
[INFO] Rule 1: org.apache.maven.enforcer.rules.version.RequireMavenVersion passed
How it works:
<phase>validate</phase>runs the goal at the very start of the lifecycle, so a wrong JDK fails in a second instead of after a long compile.[25,)is a version range meaning "25 or higher".[3.9,)means Maven 3.9 or newer.- The
<id>names the execution in the log. A plugin can have several executions, each bound to a different phase with its own configuration.
| Element | Meaning |
|---|---|
<id> | Name of the execution (must be unique within the plugin) |
<phase> | Lifecycle phase to attach to |
<goals> | One or more goals to run in that phase |
<configuration> | Settings for this execution only |
Run a Java Program With the Exec Maven Plugin
The Exec plugin (org.codehaus.mojo:exec-maven-plugin) runs your main class with the project's classpath, so you do not need to build a long java -cp command by hand.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.3</version>
<configuration>
<mainClass>com.gocourse.greeter.Greeter</mainClass>
<arguments>
<argument>Ravi</argument>
</arguments>
</configuration>
</plugin>
package com.gocourse.greeter;
public class Greeter {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "student";
System.out.println("Hello, " + name + "!");
}
}
mvn -q compile exec:java
mvn -q compile exec:java -Dexec.args="Meena"
Output:
Hello, Ravi!
Hello, Meena!
How it works:
- The
groupIdisorg.codehaus.mojo, not the Apache group, so it must be written out. Maven still finds theexecprefix becauseorg.codehaus.mojois one of its default plugin groups. exec:javaruns the class inside the Maven JVM, usingtarget/classesplus allcompileandruntimedependencies.compilecomes first becauseexec:javais a goal, not a phase, and does not compile anything itself.-Dexec.argsoverrides the<arguments>from the POM for a single run.
Build a Fat JAR With the Maven Shade Plugin
A normal JAR contains only your classes. To run an app that uses libraries with plain java -jar, the Shade plugin builds an uber JAR (fat JAR) that also contains every runtime dependency.
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.gocourse.greeter.Greeter</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>module-info.class</exclude>
<exclude>META-INF/versions/*/module-info.class</exclude>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
mvn package
ls target/*.jar
Output (shortened):
[INFO] --- shade:3.6.2:shade (default) @ greeter ---
[INFO] Including com.google.code.gson:gson:jar:2.13.2 in the shaded jar.
[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.41.0 in the shaded jar.
[INFO] Replacing original artifact with shaded artifact.
[INFO] BUILD SUCCESS
target/greeter-1.0.0.jar
target/original-greeter-1.0.0.jar
How it works:
- The
shadegoal runs inpackage, after the JAR plugin. It unpacks your JAR and every runtime dependency into one new JAR. ManifestResourceTransformerwritesMain-Classinto the manifest, sojava -jar target/greeter-1.0.0.jarworks.- The filters drop each library's
module-info.classand signature files. Several modules in one JAR are invalid, and old signatures no longer match the merged JAR. - The plain JAR is kept as
original-greeter-1.0.0.jar. Lesson Build Executable JAR compares Shade with other ways to package an app.
plugins vs pluginManagement in Maven
Both sections hold <plugin> elements, but they do different things.
| Section | Adds the plugin to this build? | Typical use |
|---|---|---|
<build><plugins> | Yes | Plugins this project actually runs, with their executions |
<build><pluginManagement> | No, only sets version and configuration | Pin versions for all modules in a parent POM |
See every plugin and binding Maven will really use with the effective POM:
mvn help:effective-pom -Doutput=effective-pom.xml
grep -A2 "<artifactId>maven-.*-plugin" effective-pom.xml | grep "<version>"
Output (shortened):
<version>3.5.0</version>
<version>3.4.0</version>
<version>3.15.0</version>
<version>3.5.6</version>
<version>3.5.0</version>
<version>3.6.3</version>
How it works:
- The effective POM is your
pom.xmlmerged with its parents, Maven's super POM and the lifecycle bindings. It is the final truth about what runs. - A plugin listed only in
pluginManagementdoes nothing until it is bound by the lifecycle or added to<plugins>. - On Windows PowerShell, use
Select-Stringinstead ofgrep, or open the file in your editor.
Real-World Example: Maven Plugins for a Course Report CLI
This project prints a JSON report of course enrolments. Its POM uses five plugins together:
| Plugin | Phase | Job |
|---|---|---|
| Enforcer | validate | Require JDK 25+ and Maven 3.9+ |
| Compiler | compile | Compile with all warnings as errors |
| Surefire | test | Run the JUnit tests |
| Shade | package | Build one runnable JAR with Gson inside |
| Exec | on demand | Run the app with mvn exec:java |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gocourse</groupId>
<artifactId>course-report</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<main.class>com.gocourse.report.ReportApp</main.class>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>6.1.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin><artifactId>maven-resources-plugin</artifactId><version>3.4.0</version></plugin>
<plugin><artifactId>maven-surefire-plugin</artifactId><version>3.5.6</version></plugin>
<plugin><artifactId>maven-jar-plugin</artifactId><version>3.5.0</version></plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.6.3</version>
<executions>
<execution>
<id>check-build-environment</id>
<phase>validate</phase>
<goals><goal>enforce</goal></goals>
<configuration>
<rules>
<requireJavaVersion><version>[25,)</version></requireJavaVersion>
<requireMavenVersion><version>[3.9,)</version></requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.15.0</version>
<configuration>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-Werror</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${main.class}</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>module-info.class</exclude>
<exclude>META-INF/versions/*/module-info.class</exclude>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.3</version>
<configuration>
<mainClass>${main.class}</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.gocourse.report;
import java.util.List;
public record CourseSummary(String course, int students, double averageMarks) {
/** Builds a summary from the marks of every student in one course. */
public static CourseSummary of(String course, List<Integer> marks) {
double average = marks.stream().mapToInt(Integer::intValue).average().orElse(0);
return new CourseSummary(course, marks.size(), Math.round(average * 10) / 10.0);
}
}
package com.gocourse.report;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.List;
import java.util.Map;
public class ReportApp {
public static void main(String[] args) {
Map<String, List<Integer>> marksByCourse = Map.of(
"Java", List.of(92, 81, 77),
"Python", List.of(78, 88));
List<CourseSummary> report = marksByCourse.entrySet().stream()
.map(entry -> CourseSummary.of(entry.getKey(), entry.getValue()))
.sorted((first, second) -> first.course().compareTo(second.course()))
.toList();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(report));
}
}
package com.gocourse.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
class CourseSummaryTest {
@Test
void averageIsRoundedToOneDecimal() {
CourseSummary summary = CourseSummary.of("Java", List.of(92, 81, 77));
assertEquals(3, summary.students());
assertEquals(83.3, summary.averageMarks());
}
@Test
void emptyCourseHasZeroAverage() {
assertEquals(0.0, CourseSummary.of("Go", List.of()).averageMarks());
}
}
Build, then run the shaded JAR:
mvn clean package
java -jar target/course-report-1.0.0.jar
Output (Maven log shortened):
[INFO] --- enforcer:3.6.3:enforce (check-build-environment) @ course-report ---
[INFO] Rule 0: org.apache.maven.enforcer.rules.version.RequireJavaVersion passed
[INFO] Rule 1: org.apache.maven.enforcer.rules.version.RequireMavenVersion passed
[INFO] --- compiler:3.15.0:compile (default-compile) @ course-report ---
[INFO] --- surefire:3.5.6:test (default-test) @ course-report ---
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jar:3.5.0:jar (default-jar) @ course-report ---
[INFO] --- shade:3.6.2:shade (default) @ course-report ---
[INFO] Including com.google.code.gson:gson:jar:2.13.2 in the shaded jar.
[INFO] BUILD SUCCESS
[
{
"course": "Java",
"students": 3,
"averageMarks": 83.3
},
{
"course": "Python",
"students": 2,
"averageMarks": 83.0
}
]
During development, skip packaging and run it straight from the classes:
mvn -q compile exec:java
How it works:
- One property, two plugins.
main.classis defined once and used by both Shade and Exec, so renaming the main class means changing one line. - Fail fast. Enforcer runs in
validate, before compiling, so a teammate on an old JDK gets a clear message instead of a confusing compiler error. - Strict compiling.
-Xlint:all -Werrorstops the build on raw types and unchecked calls, keeping the code clean. - Tests guard the JAR. Surefire runs in
test, which comes beforepackage. If the rounding inCourseSummary.ofbroke, no JAR would be built. - One file to ship. Shade merges Gson into
course-report-1.0.0.jar, so the app runs anywhere with onlyjava -jar.
The libraries a plugin packs into the JAR come from your dependencies and their scopes; see Maven Dependencies to control them. The same build in Gradle uses plugins too, as the next lesson, Gradle in Java, shows.