用法
本页记录了 Maven 调用 API 的基本用法。
你好世界
使用调用 API 最简单的方法是同时构造调用者和请求,然后简单地调用invoker.execute(request)
. 在这个例子中,我们不关心构建结果:
InvocationRequest request = new DefaultInvocationRequest(); request.setPomFile( new File( "/path/to/pom.xml" ) ); request.setGoals( Collections.singletonList( "install" ) ); Invoker invoker = new DefaultInvoker(); invoker.execute( request );
install
此代码将为定义在 的项目的生命周期阶段执行新的 Maven 构建/path/to/pom.xml
。如果构建失败,我们将保持幸福的无知......
检查退出代码
如果我们想在上面的示例中检测构建失败,我们可以简单地添加以下行:
InvocationResult result = invoker.execute( request ); if ( result.getExitCode() != 0 ) { throw new IllegalStateException( "Build failed." ); }
这将从调用结果中检索退出代码,如果不是则抛出异常0
(传统的全清除代码)。请注意,我们可以通过将InvocationOutputHandler
实例添加到invoker
或来捕获构建输出request
。
缓存调用者
由于您可以通过配置为 Maven 调用指定全局选项,因此配置单个实例并在多个方法调用中重用它Invoker
通常是有意义的:Invoker
// we will always call the same goals... private static final List<String> PUBLISH_GOALS = Arrays.asList( "clean", "site-deploy" ); // define a field for the Invoker instance. private final Invoker invoker; // now, instantiate the invoker in the class constructor... public SomeClass( File localRepositoryDir ) { Invoker newInvoker = new DefaultInvoker(); newInvoker.setLocalRepositoryDirectory( localRepositoryDir ); this.invoker = newInvoker; } // this method will be called repeatedly, and fire off new builds... public void publishSite( File siteDirectory ) throws PublishException { InvocationRequest request = new DefaultInvocationRequest(); request.setBaseDirectory( siteDirectory ); request.setInteractive( false ); request.setGoals( PUBLISH_GOALS ); InvocationResult result = invoker.execute( request ); if ( result.getExitCode() != 0 ) { if ( result.getExecutionException() != null ) { throw new PublishException( "Failed to publish site.", result.getExecutionException() ); } else { throw new PublishException( "Failed to publish site. Exit code: " + result.getExitCode() ); } } }
如您所见,我们使用相同的本地存储库位置(因为站点生成工件很可能对大多数站点都是通用的),相同的调用程序实例(已配置,我们也可以重用它),以及相同的每个构建的目标集。我们实际上可以容纳相当复杂的调用程序配置,而不会publishSite
以这种方式增加方法的复杂性。
配置 Maven 主目录
您可以使用该方法Invoker.setMavenHome()
指定它应该使用哪个 Maven 可执行文件。如果您没有为此设置提供显式值,则会通过评估系统属性和环境变量Invoker
自动尝试检测 Maven 安装。maven.home
M2_HOME
注意:如果您在Maven Surefire 插件运行的测试中使用调用 API ,您需要告诉 Surefire 将系统属性传递maven.home
给测试,以便自动 Maven 检测工作:
<project> ... <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <!-- see surefire-page for available versions --> <configuration> <systemPropertyVariables> <maven.home>${maven.home}</maven.home> </systemPropertyVariables> </configuration> </plugin> </plugins> ... </build> ... </project>