DEV Community

Thomas Dahll
Thomas Dahll

Posted on

Making a Maven-plugin that annotates auto-generated files

I have recently begun experimenting with swagger, going for an API-first approach. I was annoyed that there was no Lombok for the auto generated model files. So I reckoned that was as good time as any for learning how to make Maven plugins.

The goal, Annotate auto generated target java files. Why? So
imported Java classes are more tailored to my use.

Target files are not meant to be edited post compilation, because then they would not be equal to those in the jar file. Therefore, we need to use the Maven-phase post-process, to process the java files, before they are compiled.

First I set up an archetype for a mojo plugin.
By using the maven-plugin-annotations dependency, the definition of the parameters to use for configuring the new plugin are easy to set up.

We define that this is a plugin with the annotation @Mojo(name = "generate-annotations", defaultPhase = LifecyclePhase.PROCESS_SOURCES)

We change files that were created in the generated-source phase. So we use the next one process-source phase.,of%20your%20project's%20site%20documentation.

Here we have defined three parameters,

  • directory for which folder we want to edit the file in.
  • Imports, from where Java will import the annotations
  • Annotations, which annotations that are to be used.

These values are used to determine how the files are to be written.

To use this plugin in another project. We can update that project plugins tag, and add the configurations and metadata for the plugin.

Maven clean install, and we get the beautiful annotations that we wanted on the auto generated files.


And that's how I did the things.

Discussion (0)