示例:使用 Maven 3 生命周期扩展

生命周期参与

您可以根据需要扩展多个类:

构建你的扩展

创建一个具有依赖org.apache.maven:maven-core:3.8.5和其他依赖的 Maven 项目:

    <groupId>org.apache.maven.extensions</groupId>
    <artifactId>beer-maven-lifecycle</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-core</artifactId>
      <version>3.8.5</version>
    </dependency>

    <!-- dependency for plexus annotation -->
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-component-annotations</artifactId>
      <version>1.7.1</version>
    </dependency>

创建你的扩展类

// your extension must be a "Plexus" component so mark it with the annotation
@Component( role = AbstractMavenLifecycleParticipant.class, hint = "beer")
public class BeerMavenLifecycleParticipant extends AbstractMavenLifecycleParticipant
{

    @Override
    public void afterSessionStart( MavenSession session )
        throws MavenExecutionException
    {
      // start the beer machine
    }


    @Override
    public void afterProjectsRead( MavenSession session )
        throws MavenExecutionException
    {
      // ask a beer to the machine
    }

}

在构建扩展 jar 期间生成 plexus 元数据:

  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.plexus</groupId>
        <artifactId>plexus-component-metadata</artifactId>
        <version>1.7.1</version>
        <executions>
          <execution>
            <goals>
              <goal>generate-metadata</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      ...
    </plugins>
    ...
  </build>

在您的构建中使用您的扩展

您有 3 种在构建中使用扩展的方法:

  • 在中添加您的扩展 jar ${maven.home}/lib/ext
  • 将其作为构建扩展添加到您的 pom 中,
  • (从 Maven 3.3.1 开始)在.mvn/extensions.xml.

注意:如果您使用构建扩展机制,afterSessionStart 则不会调用该方法,因为扩展是稍后在构建中加载的

要在您的项目中使用构建扩展,请在您的 pom 中将其声明为:

   <build>
     ...
     <extensions>
       ...
       <extension>
         <groupId>org.apache.maven.extensions</groupId>
         <artifactId>beer-maven-lifecycle</artifactId>
         <version>1.0-SNAPSHOT</version>
       </extension>
       ...
     </extensions>
    ...
   </build>