是否可以从java类运行maven插件?

joh*_*ode 5 java plugins maven

需要在运行时从我的应用程序运行 Maven jaxb2 插件。是否可以?

SWo*_*ste 4

也许我做了一些可以帮助你的事情:

/**
 * @author swoeste
 * 
 */
public class MavenExecutor {

private final File       configuration;
private final ClassWorld classWorld;

/**
 * Constructor for a new maven executor.
 * 
 * @param aConfiguration
 */
public MavenExecutor( final File aConfiguration ) {
    this.configuration = aConfiguration;
    this.classWorld = new ClassWorld( "plexus.core", this.getClass().getClassLoader() ); //$NON-NLS-1$
}

/**
 * This method is used to perform a mvn  command on the given pom. The original
 * command must be given, also the sub folder and the marker folder in the working directory. The working directory
 * and the configuration file will be added before execution.
 * 
 * @param cmd the mvn command to execute
 * @param pom the absolute path to a maven pom file
 * @param output the absolute path to the working directory
 * @param folder the output sub folder of the working directory
 * @param marker the marker sub folder of the working directory
 * @return
 */
public int unpack( final String cmd, final File pom, final File output, final String folder, final String marker ) {
    final List<String> commands = new ArrayList<String>( //
            Arrays.asList( cmd.split( ConfigurationConstants.MAVEN_DELIMITER ) ) );
    commands.add( "-DoutputDirectory=" + output.getAbsolutePath() + folder ); //$NON-NLS-1$
    commands.add( "-DmarkersDirectory=" + output.getAbsolutePath() + marker ); //$NON-NLS-1$
    commands.add( "-gs=\"" + this.configuration.getAbsolutePath() + "\"" ); //$NON-NLS-1$//$NON-NLS-2$
    commands.add( "-f=\"" + pom.getAbsolutePath() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
    return MavenCli.doMain( commands.toArray( new String[commands.size()] ), this.classWorld );
}
Run Code Online (Sandbox Code Playgroud)

}

我不知道你到底想做什么,但如果你想在 Maven 项目上执行 Maven 插件,上面的代码就可以工作。就我而言,我在项目上执行 mvn dependency:unpack-dependencies 命令。

要使上述工作正常运行,您需要以下依赖项:

  <dependency>
     <groupId>org.apache.maven</groupId>
     <artifactId>maven-embedder</artifactId>
     <version>3.0.3</version>
  </dependency>
Run Code Online (Sandbox Code Playgroud)

PS:有关如何从 java 执行 Maven 事物的信息的一个很好的资源是 m2eclipse 插件的实现;)