Custom maven plugin development | Add/modify files in target, access dependencies through plugin

In this article we will develop a simple custom maven plugin.

Maven plugin example in this article

  • Attach a goal to a maven plugin.
  • Access dependency list of project.
  • Add/modify files in target directory.
  • Build & use plugin.

Create maven plugin project

Refer to these slides to get steps to create maven plugin project. Go to next section in this article for code & explanation.




Concepts of maven plugin

Here are few concepts involved in maven plugin development

  • Mojo
    • As documented in maven documentation MOJO is a play on POJO (Plain-old-Java-object), substituting “Maven” for “Plain”.
    • Mojo java class is nothing but a goal in maven. Maven build consists of lot of phases & goals so through mojo you can introduce custom goal.
    • General mojo class is annotated with @Mojo(name = “<goal-name>”) & it extends org.apache.maven.plugin.AbstractMojo class whcih provides several ready to use methods.
  • Parameters
    • parameters provide easy way to access objects associated with pom.xml, maven execution, project etc.
    • Inside mojo, @Parameter annotation can be used on instance field to get necessary objects injected.
    • Refer this to get few examples of object injection using parameters.
  • Maven Plugin Plugin (2 times plugin, not a typing mistake 🙂 )
    • This plugin generates maven plugin descriptor for our custom mojo.
    • Plugin descriptor is generated & stored in META-INF/maven/plugin.xml in a plugin’s jar artifact.

Example code

  • This is a mojo class for our plugin annotated with @Mojo & custom goal ‘modify-target”. This is extending AbstractMojo
  • We have injected MavenProject to access dependencies & target directory to add/modify files in target.
  • getLog() – This method from AbstractMojo provdes the logger of maven build so that logs from plugin are printed in same manner as that of maven build log.
  • As a best practice wrap exceptions in MojoExecutionException or MojoFailureException. MojoExecutionException causes build error (like unexpected error) & MojoFailureException causes build failure (like expected exceptions like compile issues.)



Build, publish & use

Slides in earlier section covers steps for building, publishing & using plugin. Here is the code that you have to put in other projects to use this plugin.

Here is the output generated by test project.

Get complete source code on GitHub repository



Leave a Reply

Your email address will not be published. Required fields are marked *