我正在尝试提取有关项目中使用的所有依赖项(递归)的信息。看起来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中但不通过Artifact
的getter导出的信息?
答案 0 :(得分:11)
是的,这是可能的。
我们可以使用ProjectBuilder
API在内存中构建项目:
构建项目的内存描述。
通过调用我们感兴趣的工件build(projectArtifact, request)
方法和ProjectBuildingRequest
(包含各种参数,如远程/本地存储库的位置等),这将构建一个{ {1}}内存中。
考虑以下MOJO,它将打印所有依赖项的名称:
MavenProject
这里有几个主要成分:
requiresDependencyResolution
告诉Maven我们要求在执行之前解析依赖项。在这种情况下,我将其指定为@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);
}
}
}
,以便解决所有编译和运行时依赖关系。您当然可以将其设置为ResolutionScope
。你想要的。RUNTIME
注释注入项目构建器。@Component
来覆盖当前项目,否则不会发生任何事情。当您有权访问null
时,您可以打印所有关于它的信息,例如开发人员等。
如果要打印依赖项(直接和传递),您还需要在构建请求上调用setResolveDependencies(true)
,否则,它们将不会填充在构建的项目中。