Sub topic 15
Customizing Builds with Plugins
What a Plugin Is
A plugin is a piece of code that adds work to a build. Maven and Gradle do very little by themselves. Plugins do the real jobs, such as compiling code, running tests, and making JAR files.
You already used plugins without much thought. In Maven, the Surefire plugin runs your tests. In Gradle, the application plugin adds the run task. In this chapter you will change how a plugin behaves. That change is called plugin configuration.
How Plugins Fit into Maven
In Maven, a plugin offers goals. A goal is one job the plugin can do. Maven attaches goals to lifecycle phases. When you run a phase, its goals run too.
Example: Make the JAR Runnable
mvn package builds a JAR. But java -jar target/hello-1.0-SNAPSHOT.jar fails, because the JAR does not say which class holds main. The JAR plugin can write that into the JAR's manifest. The manifest is a small file inside the JAR that describes it.
Add this inside <plugins> in your pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.1</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>Now build and run it:
mvn package
java -jar target/hello-1.0-SNAPSHOT.jarThe program prints Hello, World!.
How Plugins Fit into Gradle
In Gradle, you apply plugins in the plugins { } block at the top of build.gradle.kts. Each plugin adds tasks and settings. You change a plugin by configuring the tasks it creates.
Example: The Same Runnable JAR
The application plugin also applies the java plugin. The java plugin creates a task named jar. You can set its manifest like this:
plugins {
application
}
application {
mainClass = "com.example.App"
}
tasks.jar {
manifest {
attributes["Main-Class"] = "com.example.App"
}
}Build and run it:
./gradlew jar
java -jar build/libs/hello.jarThe JAR name comes from your project folder name. Check build/libs if your file has a different name.
Maven and Gradle Side by Side
| Idea | Maven | Gradle |
|---|---|---|
| Where plugins go | `<build><plugins>` in `pom.xml` | `plugins { }` in `build.gradle.kts` |
| Unit of work | Goal, bound to a phase | Task |
| How you customize | `<configuration>` element | Configure the task or extension |
Exercise
You want Maven's JAR plugin to set the main class to com.example.Tool. Which element inside <manifest> do you change, and which command builds the JAR?
Show answer
Change the <mainClass> element to com.example.Tool, then run mvn package. The jar:jar goal runs during the package phase and writes the main class into the manifest.
Exercise
In Gradle, which plugin creates the jar task, and how did it get applied in the example above?
Show answer
The java plugin creates the jar task. The application plugin applies the java plugin automatically, so you did not need to list it.