Issue
I'm developing custom Maven plugin. I want my plugin to add a new dependency to a project.
I have the following code:
@Mojo(name = "generate-model", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class ModelGeneratorMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject project;
@Override
public void execute() throws MojoExecutionException {
Dependency connectivity = new Dependency();
connectivity.setGroupId("groupid");
connectivity.setArtifactId("artifactid");
connectivity.setVersion("1.0");
//noinspection unchecked
project.getDependencies().add(connectivity);
}
}
It seems to have no effect, because when I compile a project containing this plugin, I get unresolved symbol error.
I'm sure that plugin is executed because I see code generated by it (code generation is omitted in my example) in target
folder.
Solution
I think you should bind the goal
in your plugin to the Initialize
phase of Maven build process to include the dependency very early in the build process.
Something along these lines:
@Mojo(name = "generate-model", defaultPhase = LifecyclePhase.INITIALIZE)
public class ModelGeneratorMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject project;
@Parameter(defaultValue = "${session}", required = true)
MavenSession session;
@Override
public void execute() throws MojoExecutionException {
Dependency connectivity = new Dependency();
connectivity.setGroupId("groupid");
connectivity.setArtifactId("artifactid");
connectivity.setVersion("1.0");
project.getDependencies().add(connectivity);
session.setCurrentProject(project);
}
}
<plugin>
<groupId>com.maventest</groupId>
<artifactId>maven-generate-model</artifactId>
<version>1.0-SNAPSHOT</version>
<executions>
<execution>
<goals>
<goal>generate-model</goal>
</goals>
</execution>
</executions>
</plugin>
I tried multiple paths to accomplish this, but it seems not possible to do using maven plugins, probably maven extension is a better choice here.
The reason is that Depedency Resolution is the first step into Maven lifecycle and you need that extra dependency to compile the application. With maven extensions, you can extend the maven lifecycle. https://maven.apache.org/examples/maven-3-lifecycle-extensions.html
Answered By - Jahan