本页记录了 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 );
此代码将在/path/to/pom.xml中定义的项目的安装生命周期阶段执行新的 Maven 构建。如果构建失败,我们将保持幸福的无知......
如果我们想在上面的示例中检测构建失败,我们可以简单地添加以下行:
InvocationResult result = invoker.execute( request );
if ( result.getExitCode() != 0 )
{
throw new IllegalStateException( "Build failed." );
}
这将从调用结果中检索退出代码,如果它不为 0(传统的全清除代码)则抛出异常。请注意,我们可以通过将InvocationOutputHandler实例添加到调用者或请求来捕获构建输出。
由于您可以通过Invoker配置为 Maven 调用指定全局选项,因此配置单个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() );
}
}
}
如您所见,我们使用相同的本地存储库位置(因为站点生成工件很可能对大多数站点都是通用的),相同的调用程序实例(已配置,我们也可以重用它),以及相同的每个构建的目标集。我们实际上可以适应 Invoker 的相当复杂的配置,而不会以这种方式增加publishSite方法的复杂性。
您可以使用方法Invoker.setMavenHome()来指定它应该使用哪个 Maven 可执行文件。如果您没有为此设置提供明确的值,Invoker将通过评估系统属性maven.home和环境变量M2_HOME自动尝试检测 Maven 安装。
注意:如果您在Maven Surefire 插件运行的测试中使用调用 API ,您需要告诉 Surefire 将系统属性maven.home传递给测试,以便自动 Maven 检测工作:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version> <!-- see surefire-page for available versions -->
<configuration>
<systemPropertyVariables>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
...
</build>
...
</project>