java – Maven Plugin API:从Artifact获取MavenProject
作者:互联网
我试图提取有关我的项目中使用的所有依赖项(递归)的信息.看起来MavenProject类提供了我需要的所有信息.但我无法弄清楚如何将Artifact的实例转换为MavenProject的实例
/**
*
*
* @reqiresDependencyResolution
*
*/
@Mojo(name = "license-overview", defaultPhase = LifecyclePhase.PROCESS_SOURCES)
public class MyMojo extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
MavenProject project;
public void execute() throws MojoExecutionException {
Set<Artifact> artifacts= project.getArtifacts();
for (Artifact artifact : artifacts) {
//Here I need to access the artifact's name, license, author, etc.
System.out.println("*** "+artifact.getArtifactId()+"***");
}
}
}
如何访问位于我的依赖关系的pom中但不通过Artifacts getters导出的信息?
解决方法:
是的,这是可能的.
我们可以使用ProjectBuilder
API在内存中构建一个项目:
Builds in-memory descriptions of projects.
通过调用我们感兴趣的工件的build(projectArtifact, request)
方法和ProjectBuildingRequest
(包含远程/本地存储库的位置等各种参数等),这将在内存中构建MavenProject.
考虑以下MOJO,它将打印所有依赖项的名称:
@Mojo(name = "foo", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class MyMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
@Component
private ProjectBuilder projectBuilder;
public void execute() throws MojoExecutionException, MojoFailureException {
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
try {
for (Artifact artifact : project.getArtifacts()) {
buildingRequest.setProject(null);
MavenProject mavenProject = projectBuilder.build(artifact, buildingRequest).getProject();
System.out.println(mavenProject.getName());
}
} catch (ProjectBuildingException e) {
throw new MojoExecutionException("Error while building project", e);
}
}
}
这里有几个主要成分:
> requiresDependencyResolution
告诉Maven我们要求在执行之前解析依赖项.在这种情况下,我将其指定为RUNTIME,以便解决所有编译和运行时依赖性.您当然可以将其设置为您想要的ResolutionScope
.
>使用@Component注释注入项目构建器.
>使用当前Maven会话的参数构建默认构建请求.我们只需要通过显式设置为null来覆盖当前项目,否则什么都不会发生.
当您有权访问MavenProject时,您可以打印所有关于它的信息,比如开发人员等.
如果要打印依赖项(直接和传递),还需要在构建请求上调用setResolveDependencies(true)
,否则,它们将不会填充在构建的项目中.
标签:java,maven,maven-plugin 来源: https://codeday.me/bug/20191001/1837920.html