jwa
jwa

Reputation: 3281

Custom Maven Plugin: Programmatically Adding Source Directory to Project

As a Maven end-user, it is simple to add an additional directory to the list of source directories that will be compiled during the "compile" phase. I would use the build-helper-maven-plugin approach.

However, in my own custom plugin I would like to do this programmatically. My plugin will generate some java code. I would subsequently like to add the output directory (containing generated .java files) to the list of source paths.

At the moment I’m manually having to set the build-helper-maven-plugin config in all of my POMs to get the files I’m generating to be compiled.

Any pointers on what part of the Maven API to be looking at? My searches have only yielded queries from end-users, which are solved with the build-helper-maven-plugin approach.

Upvotes: 3

Views: 886

Answers (1)

jwa
jwa

Reputation: 3281

To find my answer I took a look at the source code for the ANTLR maven plugin, which I know adds sources to the path. See AbstractAntlrMojo.

The solution is to add a MavenProject member variable to your Mojo with an expression to bind it to the project:

@Parameter(defaultValue="${project}")
private MavenProject project;

Once one has a reference to the project, it's a simple method invocation:

project.addCompileSourceRoot("<DIRECTORY-PATH-HERE>");

This will ensure that the new directories housing generated code will be compiled.

Upvotes: 4

Related Questions