Examining Dependencies in Maven Plugins

2 minute read Published:

After you’ve worked with Maven for a while, you’ll eventually find a need to extend it. While there are some means of executing arbitrary code as part of your build, the best way to handle such needs is to create a maven plugin. The task may seem a bit daunting at first, but you’ll learn a lot about how maven works by doing it. Listed below are the properties that you need to define to examine the dependencies of a maven project from within a plugin. The following code would be placed inside a Maven Mojo.

/** @parameter default-value="${project}" */
private MavenProject mavenProject;

/** @parameter default-value="${localRepository}" */
private ArtifactRepository localRepository;

/** @component */
private ArtifactFactory artifactFactory;

/** @component */
private ArtifactResolver resolver;

/** @component */
private ArtifactMetadataSource artifactMetadataSource;

The @parameter annotation will bind maven properties to the annotated property. You can refer to many properties on common Maven interfaces. The @component annotation binds Plexus components from maven’s DI framework. Unfortunately I’ve yet to find a single, concise documentation source, but the Codehaus Mojo Cookbook and the Maven API doc will point you in the right direction.

Set<Artifact> artifacts = mavenProject.createArtifacts(
    artifactFactory,
    null,
    new GroupIdFilter("com.mydomain")
);

ArtifactResolutionResult arr = resolver.resolveTransitively(
    artifacts,
    mavenProject.getArtifact(),
    mavenProject.getRemoteArtifactRepositories(),
    localRepository,
    artifactMetadataSource
);

Set<Artifact> completeDependencies = arr.getArtifacts();

for(Artifact art : completeDependencies) {
  // do something interesting
}

Once you have access to all the needed properties, you can use code similar to the above to examine the dependencies of your project. This particular snippet will collect all dependencies and transitive dependencies for artifacts with a group id of “com.mydomain” into the completeDependencies set. GroupIdFilter is a simple implementation of the ArtifactFilter interface. Note that these are the dependencies of the project that the plugin is executing in, not just those of the plugin itself.

JarFile jar = new JarFile(artifact.getFile());

The ability to determine all of the transitive dependencies of your project like this can be very powerful. Once you get ahold of an artifact, you can easily create a JarFile and inspect its manifest, entries or whatever you’re interested in. This allows you to do things like create artifacts that contain code or configuration that feeds into your build process, and automatically discover and take action merely by adding them as a project dependency.