在 Maven 插件之外,对工件进行操作的方式是通过 Aether。该团队有一个示例项目来获取给定工件的传递依赖项,称为ResolveTransitiveDependencies
. 一旦你设置了 Aether 依赖项(如这里所示),你可以简单地拥有:
public static void main(final String[] args) throws Exception {
DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
RepositorySystem system = newRepositorySystem(locator);
RepositorySystemSession session = newSession(system);
RemoteRepository central = new RemoteRepository.Builder("central", "default", "http://repo1.maven.org/maven2/").build();
Artifact artifact = new DefaultArtifact("group.id:artifact.id:version");
CollectRequest collectRequest = new CollectRequest(new Dependency(artifact, JavaScopes.COMPILE), Arrays.asList(central));
DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
DependencyRequest request = new DependencyRequest(collectRequest, filter);
DependencyResult result = system.resolveDependencies(session, request);
for (ArtifactResult artifactResult : result.getArtifactResults()) {
System.out.println(artifactResult.getArtifact().getFile());
}
}
private static RepositorySystem newRepositorySystem(DefaultServiceLocator locator) {
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
return locator.getService(RepositorySystem.class);
}
private static RepositorySystemSession newSession(RepositorySystem system) {
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
LocalRepository localRepo = new LocalRepository("target/local-repo");
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
return session;
}
它将下载工件并将它们放入"target/local-repo"
.
请注意,您可以在系统会话中使用DefaultProxySelector
和配置代理和镜像。DefaultMirrorSelector
可以读取 Maven 设置文件并使用它来填充会话,但事情变得非常丑陋非常快......
当您想要与 Maven 本身紧密耦合时,因为您可以访问 POM 进行处理并希望将设置考虑在内,直接以编程方式调用 Maven 会简单得多。在这种情况下,您对给定 POM 文件的每个依赖项(包括传递依赖项)的路径感兴趣。为此,dependency:list
目标以及设置outputAbsoluteArtifactFilename
totrue
将(几乎)完全实现。
要以编程方式调用 Maven,可以使用Invoker API。将依赖项添加到您的项目中:
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>2.2</version>
</dependency>
你可以有:
InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile(new File(pomPath));
request.setGoals(Arrays.asList("dependency:list"));
Properties properties = new Properties();
properties.setProperty("outputFile", "dependencies.txt"); // redirect output to a file
properties.setProperty("outputAbsoluteArtifactFilename", "true"); // with paths
properties.setProperty("includeScope", "runtime"); // only runtime (scope compile + runtime)
// if only interested in scope runtime, you may replace with excludeScope = compile
request.setProperties(properties);
Invoker invoker = new DefaultInvoker();
// the Maven home can be omitted if the "maven.home" system property is set
invoker.setMavenHome(new File("/path/to/maven/home"));
invoker.setOutputHandler(null); // not interested in Maven output itself
InvocationResult result = invoker.execute(request);
if (result.getExitCode() != 0) {
throw new IllegalStateException("Build failed.");
}
Pattern pattern = Pattern.compile("(?:compile|runtime):(.*)");
try (BufferedReader reader = Files.newBufferedReader(Paths.get("dependencies.txt"))) {
while (!"The following files have been resolved:".equals(reader.readLine()));
String line;
while ((line = reader.readLine()) != null && !line.isEmpty()) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
// group 1 contains the path to the file
System.out.println(matcher.group(1));
}
}
}
这将创建一个调用请求,其中包含:要调用的目标和系统属性,就像您mvn dependency:list -Dprop=value
在命令行上启动一样。要使用的设置的路径将默认为 的标准位置"${user.home}/settings.xml"
,但也可以使用 和 指定设置的request.setUserSettingsFile(...)
路径request.setGlobalSettingsFile(...)
。调用者需要设置 Maven 主目录(即安装目录),但"maven.home"
前提是未设置系统属性。
调用的结果dependency:list
被重定向到一个文件,该文件稍后会进行后处理。该目标的输出包含格式中的依赖项列表(分类器可能不存在,如果没有):
group.id:artifact.id:type[:classifier]:version:scope:pathname
没有办法只输出已解析工件文件的路径,并且分类器可能不存在的事实使解析有点复杂(我们不能:
限制拆分,因为路径可能包含:
.. .)。首先,已解析的工件位于输出文件中的行下方"The following files have been resolved:"
,然后,由于所需范围仅为compile
or runtime
,我们可以使用简单的正则表达式获取工件文件的路径,该表达式采用compile:
or之后的所有内容runtime:
。然后该路径可以直接用作new File
.
如果后处理过程中的箍看起来太脆弱,我想您可以创建自己的插件,只输出已解析工件的文件名。