如何编译在运行时生成的java文件

时间:2017-11-03 12:10:37

标签: maven plugins runtime exec-maven-plugin

我希望编译由Code Generate.java在运行时生成的类。我成功地能够在运行时通过exec-maven-plugin运行Generate.java。它在generated-source-java中生成代码。但是这段代码没有被编译。我也想将它们添加到一个jar中,因为我正在使用maven-assembly-plugin 这是我的pom快照。

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
      <execution>
      <id>build-test-environment</id>
      <phase>generate-test-resources</phase>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
    </executions>
    <configuration>
      <mainClass>com.test.Generate</mainClass>
    </configuration>
  </plugin>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <executions>
      <execution>
        <phase>prepare-package</phase>
        <goals>
          <goal>add-source</goal>
        </goals>
        <configuration>
          <sources>
            <source>${project.build.directory}/generated-sources-java</source>
          </sources>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <finalName>test</finalName>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <appendAssemblyId>false</appendAssemblyId>
    </configuration>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

1 个答案:

答案 0 :(得分:1)

你很亲密;插件需要绑定到不同的阶段。目前,配置是在prepare-package阶段添加新的源目录,这在所有内置编译完成后发生。如果将其配置为在生命周期的早期运行,我认为一切都会正常工作。&#34;

操纵测试代码的阶段是:

  • 生成测试来源
  • process-test-sources
  • 生成测试资源
  • 过程测试资源
  • test-compile

对于这种情况,我会改变配置,如下所示:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.5.0</version>
  <executions>
    <execution>
      <id>build-test-environment</id>
      <phase>generate-test-sources</phase>  <!-- generating source code -->
      <!-- rest of config -->
    </execution>
  </executions>
      <!-- rest of config, consider moving into specific execution -->
</plugin>
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>add-test-sources</id>
      <phase>process-test-sources</phase>  <!-- do something with generated test sources -->
      <goals>
        <goal>add-test-source</goal>
      </goals>
      <!-- rest of config -->
  </execution>
</executions>

请注意,我也更改了build-helper-maven-plugin目标(至add-test-source),因为这是我们正在处理的测试代码。

Maven Lifecycle概述文档中的更多详细信息。