在Maven插件中执行Maven构建

时间:2014-04-04 18:50:44

标签: java maven maven-plugin

我正在开发一个maven插件,除其他外,它将在项目上运行mvn compile

我尝试将此添加到扩展AbstractMojo的类(类似于https://github.com/rzymek/watcher-maven-plugin):

@Component
private Maven maven;
...
maven.execute(request);

抱怨maven为null。所以我试过了:

Maven maven = new DefaultMaven();
maven.execute(request);

但是这会在org.apache.maven.DefaultMaven.execute(DefaultMaven.java:170)中导致NullPointerException,如此未提问题Programmatic builds using Maven 3 API

中所述

我也试过

ClassRealm containerRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
ContainerConfiguration cc = new DefaultContainerConfiguration().setName( "maven" ).setRealm( containerRealm ).setClassPathScanning( PlexusConstants.SCANNING_INDEX ).setAutoWiring( true );

DefaultPlexusContainer container = new DefaultPlexusContainer( cc );
Maven maven = (Maven) container.lookup( "org.apache.maven.Maven", "default" );
maven.execute(request);

但是它引发了NoSuchElementException:

org.codehaus.plexus.component.repository.exception.ComponentLookupException: java.util.NoSuchElementException
  role: org.apache.maven.Maven
  roleHint: default

我尝试使用getPluginContext()中的角色提示,结果相同。

1 个答案:

答案 0 :(得分:0)

你需要告诉maven生成插件描述文件:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-plugin-plugin</artifactId>
            <version>3.2</version>
            <configuration>
                <!-- see http://jira.codehaus.org/browse/MNG-5346 -->
                <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
            </configuration>
            <executions>
                <execution>
                    <id>mojo-descriptor</id>
                    <goals>
                        <goal>descriptor</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- ... -->
    </plugins>
</build>