4

I wrote a plugin which should execute at compile phase. It generates some source code which is being used by other Java classes.

When I normally add this plugin in my POM, I face a compilation error because Maven first execute the compiler plugin and then my plugin. So while compiling, it fails because it need the source code which is generated by my own plugin.

How do I resolve this problem?

0

1 Answer 1

3

The fix is to invoke your plugin before the compilation of the sources. Compilation, as done by maven-compiler-plugin:compile, happens by default in the compile phase of the default lifecycle.

Before that compile phase, the default lifecycle also invokes the generate-sources, which purpose is to:

generate any source code for inclusion in compilation.

Therefore, you should bind your plugin to the phase generate-sources instead of the compile phase. This can either be done using the defaultPhase attribute of your MOJO with

@Mojo(name = "example", defaultPhase = LifecyclePhase.GENERATE_SOURCES) 

or declaring it explicitely in the POM in its executions:

<execution> <phase>generate-sources</phase> <!-- id, goal and configuration --> </execution> 

You'll need to make sure the classes you generated in that phase are correctly added to the buildpath. If the plugin doesn't do it already (by calling MavenProject.addCompileSourceRoot(directory)), you can make use of the build-helper-maven-plugin:add-source goal to add the directory where the sources have been generated to the buildpath.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I was stuck in a similar issue registering the protobuf-maven-plugin inside my project. I was trying to register this plugin on the compile phase which failed with the same error as @Anuj reported above in the original question. The default phase binding of the plugin was already done with generate-sources which worked without extra configuration. BTW, you mention this: "Compilation, as done by maven-compiler-plugin:compile, happens by default in the compile phase of the default lifecycle". Is this documented ? Or this is understood as is ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.