Forking Java using the Exec Maven Plugin, without

2019-06-16 19:10发布

问题:

From the documentation:

  1. exec:exec execute programs and Java programs in a separate process.
  2. exec:java execute Java programs in the same VM.

I want to fork a java program. I've already got it working in exec:java but that doesn't fork. So the obvious move is to change the goal to exec. Problem is, the syntax for exec is pretty different from the syntax of java. It doesn't have tags like includeProjectDependencies, includePluginDependencies, etc. Is there a plugin I can use that is like #1 in the sense that it forks, but has a convenient syntax like #2? IMO, #2 should just have a <fork>true</fork> configuration.

回答1:

I think you can stick to exec:exec, using that kind of configuration if you want to give the project classpath to the Java process you use:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <configuration>
        <executable>java</executable>
        <longClasspath>true</longClasspath>
        <arguments>
            <argument>-XX:MaxPermSize=128M</argument>
            <argument>-Xmx1024M</argument>
            <argument>-Xdebug</argument>
            <argument>-Xrunjdwp:transport=dt_socket,address=8888,server=y,suspend=n</argument>
            <argument>-classpath</argument>
            <classpath/>
        </arguments>
    </configuration>
</plugin>

See also the plugin Usage page



回答2:

It's also possible to spawn a Java process from Maven with the maven-antrun-plugin. This plugin exports several classpaths covering the compile/runtime/test scopes, as well as the plugin dependencies.

Executing a class in a separate process with the compile and plugin dependencies would thus look like this:

<plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <goals>
    <goal>run</goal>
  </goals>
  <configuration>
    <target>
      <java classname="com.example.MainClass" fork="true">
        <classpath>
          <path refid="maven.compile.classpath"/>
          <path refid="maven.plugin.classpath"/>
        </classpath>
      </java>
    </target>
  </configuration>
</plugin>

This is executed with mvn antrun:run instead of exec:exec.