17.6.2. 创建自定义的生命周期

自定义生命周期必须在插件项目的META-INF/maven/lifecycle.xml文件中定义。你可以引入这个定义在src/main/resources下的META-INF/maven/lifecycle.xml文件。以下的lifecycle.xml声明了一个名为zipcycle的生命周期,它在package阶段包含了一个zip目标。

Example 17.9. 在lifecycle.xml中自定义生命周期

<lifecycles>
  <lifecycle>
    <id>zipcycle</id>
    <phases>
      <phase>
        <id>package</id>
        <executions>
          <execution>
            <goals>
              <goal>zip</goal>
            </goals>
          </execution>
        </executions>
      </phase>
    </phases>
  </lifecycle>
</lifecycles>


如果你想要在另一个构建中运行这个zipcycle生命周期,你可以创建一个ZipForkMojo,然后使用@execute注解来告诉Maven,当ZipForkMojo运行的时候,逐步通过zipcycle生命周期的阶段。

Example 17.10. 在Mojo中Fork一个自定义生命周期

/**
 * Forks a zip lifecycle.
 * @goal zip-fork
 * @execute lifecycle="zipcycle" phase="package"
 */
public class ZipForkMojo extends AbstractMojo
{
  public void execute()
    throws MojoExecutionException
  {
    getLog().info( "doing nothing here" );
  }
}


运行ZipForkMojo的时候会fork出另一个生命周期。如果你配置了你插件的前缀为zip,运行zip-fork会得到类似于如下输出的结果:

$ mvn zip:zip-fork
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'zip'.
[INFO] ----------------------------------------------------------------------------
[INFO] Building Maven Zip Forked Lifecycle Test
[INFO]    task-segment: [zip:zip-fork]
[INFO] ----------------------------------------------------------------------------
[INFO] Preparing zip:zip-fork
[INFO] [site:attach-descriptor]
[INFO] [zip:zip]
[INFO] Building zip: ~/maven-zip-plugin/src/projects/zip-lifecycle-test/target/output.zip
[INFO] [zip:zip-fork]
[INFO] doing nothing here
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Sun Apr 29 16:10:06 CDT 2007
[INFO] Final Memory: 3M/7M
[INFO] ------------------------------------------------------------------------

调用zip-fork会衍生出另外一个生命周期,Maven运行zipcycle生命周期,然后从ZipFormMojo的execute方法打印信息。