简体   繁体   English

如何从 Java 运行 Maven?

[英]How to run Maven from Java?

I want to execute Maven command from Java for development of a plugin.我想从 Java 执行 Maven 命令来开发插件。 I tried maven-embedder but looks like it is now not supported.我试过maven-embedder但看起来现在不支持。 Is someone aware of some other tool which can be used?有人知道可以使用的其他工具吗?

A simple invocation API : maven-invoker.一个简单的调用 API:maven-invoker。

Project documentation : http://maven.apache.org/shared/maven-invoker/项目文档: http : //maven.apache.org/shared/maven-invoker/

Usage : http://maven.apache.org/shared/maven-invoker/usage.html用法: http : //maven.apache.org/shared/maven-invoker/usage.html

InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile( new File( "/path/to/pom.xml" ) );
request.setGoals( Arrays.asList( "clean", "install" ) );

Invoker invoker = new DefaultInvoker();
invoker.execute( request );

Use Maven Embedder使用Maven 嵌入器

Maven embedder is still supported and easy to configure, so this is better option for you. Maven 嵌入器仍受支持且易于配置,因此这对您来说是更好的选择。

Java code Java代码

MavenCli cli = new MavenCli();
cli.doMain(new String[]{"clean", "install"}, "project_dir", System.out, System.out);

Project configuration项目配置

<dependencies>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-embedder</artifactId>
        <version>3.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.aether</groupId>
        <artifactId>aether-connector-wagon</artifactId>
        <version>0.9.0.M2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.wagon</groupId>
        <artifactId>wagon-http-lightweight</artifactId>
        <version>2.5</version>
    </dependency>
</dependencies>

Fully working example: https://github.com/mariuszs/maven-cli-example完整工作示例: https : //github.com/mariuszs/maven-cli-example

Maven embedder is indeed no longer supported (only hudson still uses it). Maven 嵌入器确实不再受支持(只有 hudson 仍在使用它)。 But, as in hudson, there are several other ways to run maven.但是,就像在 hudson 中一样,还有其他几种运行 maven 的方法。 You could simply run maven as an external program:您可以简单地将 maven 作为外部程序运行:

Runtime.getRuntime().exec("mvn clean install");

Or you could consider creating an ant script for maven.或者你可以考虑为 maven创建一个ant 脚本。 This script could then be called either as an external program or (if you need more control) adding ant to your classpath and calling the Antrunner.然后可以将此脚本作为外部程序调用,或者(如果您需要更多控制)将 ant 添加到类路径并调用 Antrunner。

UPDATE更新

Maven embedder is now supported again so that is your best option.现在再次支持 Maven 嵌入器,因此这是您的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM