This page looks best with JavaScript enabled

Mastering Maven Create Custom Maven Plugin

 ·  ☕ 4 min read  ·  ✍️ Dinesh Arora

Creating a custom Maven plugin to count the number of dependencies in a project can be a useful addition to your build process, especially when you want to keep track of your project’s dependencies. Below, I’ll provide a step-by-step guide along with detailed code examples to help you achieve this.

First, ensure you have Maven installed on your system. You can check this by running mvn -version in your terminal.

Now, create a new Maven project or use an existing one where you want to add this custom plugin. For demonstration purposes, let’s create a new Maven project named “DependencyCounterPluginDemo

That’s when the need to undo local Git commits arises. We want to rewind the clock and make things right. Let’s dig into how you can do that.

1
mvn archetype:generate -DgroupId=com.example -DartifactId=DependencyCounterPluginDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Change into your project directory:

1
cd DependencyCounterPluginDemo

Open the pom.xml file of your project and add the plugin configuration. This configuration specifies the Maven plugin you want to create and provides details about its execution.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<build>
    <plugins>
        <plugin>
            <groupId>com.javahabit</groupId>
            <artifactId>dependency-counter-plugin</artifactId>
            <version>1.0-SNAPSHOT</version>
            <executions>
                <execution>
                    <phase>compile</phase>
                    <goals>
                        <goal>count-dependencies</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Now, let’s create the Maven plugin project. In your project’s root directory, create a new directory named dependency-counter-plugin:

1
mkdir dependency-counter-plugin

Inside the dependency-counter-plugin directory, create a Java class that will implement the custom plugin. Let’s name it DependencyCounterMojo.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.example.dependencycounterplugin;

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

@Mojo(name = "count-dependencies")
public class DependencyCounterMojo extends AbstractMojo {

    public void execute() throws MojoExecutionException {
        // Your logic to count dependencies goes here
        // For demonstration, we'll just print a message.
        getLog().info("Counting dependencies...");
    }
}

Back in your project’s root directory (where the pom.xml is located), build the custom plugin using Maven:

1
mvn clean install

This will compile your plugin and install it in your local Maven repository.

To run the custom Maven plugin, you can execute the compile phase (or any other phase where you configured your plugin to run) of your project:

1
mvn compile

In this example, we configured the custom plugin to execute during the compile phase.

Inside the DependencyCounterMojo class, you can implement the logic to count project dependencies. For this example, we’ll use the ProjectBuilder and ArtifactResolver from the Maven API to get the project’s dependencies and count them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.apache.maven.shared.artifact.ArtifactResolver;
import org.apache.maven.shared.artifact.DefaultArtifactCoordinate;
import org.apache.maven.shared.artifact.resolve.ArtifactResolverException;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.logging.Logger;

import java.util.List;

@Mojo(name = "count-dependencies")
public class DependencyCounterMojo extends AbstractMojo {

    // Define the components we need to interact with Maven's internals
    private PlexusContainer container;
    private MavenProject project;
    private Logger logger;
    private ArtifactResolver artifactResolver;

    public void execute() throws MojoExecutionException {
        try {
            // Fetch the project's dependencies
            List<Dependency> dependencies = project.getDependencies();

            // Fetch dependencies from dependency management if present
            DependencyManagement dependencyManagement = project.getDependencyManagement();
            if (dependencyManagement != null) {
                dependencies.addAll(dependencyManagement.getDependencies());
            }

            int dependencyCount = dependencies.size();
            getLog().info("Total number of dependencies: " + dependencyCount);
        } catch (Exception e) {
            throw new MojoExecutionException("Error counting dependencies", e);
        }
    }
}

Execute the custom Maven plugin by running the following Maven command in your project’s root directory:

1
mvn compile

This will execute the count-dependencies goal of your custom plugin during the compile phase, and it will print the total number of dependencies in your project.

Congratulations! You’ve created a custom Maven plugin to count the number of dependencies in your project. You can further enhance this plugin to perform additional tasks or integrate it into your build process as needed.

Happy Coding!

Share on
Support the author with

Dinesh Arora
WRITTEN BY
Dinesh Arora
Developer