【问题标题】:Is it possible to run maven plugin from java class?是否可以从 java 类运行 maven 插件?
【发布时间】:2012-04-20 10:16:36
【问题描述】:

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

【问题讨论】:

  • 在软件中一切皆有可能。愿意提供一些细节吗?
  • 为什么要运行maven插件?我怀疑你需要做一些与 JAXB 相关的事情吗?然后直接使用 JAXB API。我相信这是可能的,但需要做很多工作才能让它发挥作用。该插件不能单独运行,它需要 Maven 环境,最重要的是 pom.xml
  • @maksimov 事实上,在软件中一切都是不可能的;)

标签: java plugins maven


【解决方案1】:

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

/**
 * @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 );
}

}

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

要实现上述工作,您需要此依赖项:

  <dependency>
     <groupId>org.apache.maven</groupId>
     <artifactId>maven-embedder</artifactId>
     <version>3.0.3</version>
  </dependency>

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

【讨论】:

    【解决方案2】:

    我确实需要它,当然可以。只需下载插件的源代码并查看里面发生了什么。您可以实例化一个适当的 Mojo(实现插件目标的类)并执行它。但是,通常插件的目标在很大程度上取决于 Maven 项目上下文,这可能很难提供(甚至以某种方式模拟),因此 Mojo 能够无错误地执行。

    我不知道你的具体情况,但我有 99% 的把握,根据你在插件源代码中找到的内容(可能是不要自己写所有东西)。

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2015-12-28
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多