以编程方式使用 Maven

Dav*_*lla 7 maven

我需要制作一个小程序来下载 Maven 项目并打印其依赖项

像这样的东西:

MavenArtifactRepository repository = new MavenArtifactRepository("typesafe", "http://repo.typesafe.com/typesafe/releases/", ..., ..., ...);
downloadAndPrintDependencies(repository, "org.hsqldb", "hsqldb", "2.2.9");

void downloadAndPrintDependencies(repository, groupId, artifactId, version) {
  MavenProject projectDescription = new MavenProject("org.hsqldb", "hsqldb", "2.2.9");
  Artifact artifact = repository.getProject(projectDescription);  // this would download the artificat in the local repository if necessary

  List<Dependency> dependecies = artifact.getDependencies();
  ...
}
Run Code Online (Sandbox Code Playgroud)

并且,它可以在 Maven 项目上执行目标,如下所示:

String pomXmlFile = "/tmp/myproject/pom.xml";
Reader reader = new FileReader(pomXmlFile);
MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
Model model = xpp3Reader.read(reader);

ProjectArtifact projectArtifact = new ProjectArtifact(model);
projectArtifact.clean();
projectArtifact.install();
Run Code Online (Sandbox Code Playgroud)

对伪代码有任何反馈吗?

从存储库获取工件的正确类和函数是什么?

在 Maven 项目上执行目标(例如 clean 和 install)的正确类和函数是什么?

mgu*_*mon 4

好的

我有一个项目 Naether,它是 Maven 依赖解析库 Aether 的包装器。

使用Naether,您可以解决依赖关系

import com.tobedevoured.naether.api.Naether;
import com.tobedevoured.naether.impl.NaetherImpl;

Naether naether = new NaetherImpl();
naether.addDependency( "ch.qos.logback:logback-classic:jar:0.9.29" );
naether.addDependency( "junit:junit:jar:4.8.2" );
naether.resolveDependencies();
System.out.println( naether.getDependenciesNotation().toString() );
Run Code Online (Sandbox Code Playgroud)

将输出:

["ch.qos.logback:logback-core:jar:0.9.29",
 "ch.qos.logback:logback-classic:jar:0.9.29",
 "junit:junit:jar:4.8.2",
 "org.slf4j:slf4j-api:jar:1.6.1" ]
Run Code Online (Sandbox Code Playgroud)

坏处

我不知道如何通过Java构建(例如编译源代码)pom.xml。我搜索了一下,但没有找到具体的例子。ProjectArtifact只是 Maven 用于解析 POM(例如父 POM)的工件描述符它不公开构建操作。由于构建 Maven 项目的方法有一百万种,因此没有简单的安装方法。您必须以某种方式开始安装过程的生命周期。

Naether 可以做什么,首先构建项目并让Naether 安装它:

import com.tobedevoured.naether.api.Naether;
import com.tobedevoured.naether.impl.NaetherImpl;

Naether naether = new NaetherImpl();
naether.install( "com.example:sample:0.0.1", "/tmp/myproject/pom.xml", "/tmp/myproject/target/sample-0.0.1.jar" )
Run Code Online (Sandbox Code Playgroud)

更新 - 这一切是如何结合在一起的?

项目的构建、部署、安装等都很复杂。Maven 在简化它方面做得非常好。尽管 Maven 任务只是install,但要使其发挥作用还涉及许多步骤。对于一个简单的 Java 项目,这意味着填充类路径、编译源代码、打包 jar,然后将其安装到本地 Maven 存储库中。当您谈论打包 Java 项目的其他方法(例如war )时,事情只会变得更加复杂。

Maven 的人员做了艰苦的工作,并将依赖解析剥离到自己的库Aether中。这完成了处理工件的所有繁重工作。Aether 可让您找出项目的依赖项,下载依赖项。Aether 还允许您在本地安装工件或将其部署到远程存储库。

Aether 不做的是管理项目。它不会清理目标目录或编译源。

我用 Naether 创建的只是一种访问 Aether 的简化方法。