适用于测试和主要版本的不同Maven编译器版本


问题内容

如何配置Maven编译器以将Java 5用于测试代码并将Java 1.4用于主代码?


问题答案:

如果要设置对相关Java版本的遵从性,则可以为每次执行配置编译器插件。假设Maven使用的JDK至少与您指定的最高版本相同。通过使用属性,可以在命令行或子项中覆盖该配置(如果需要):

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <source>${compileSource}</source>
    <target>${compileSource}</target>
  </configuration>
  <executions>
    <execution>
      <id>test-compile</id>
      <phase>process-test-sources</phase>
      <goals>
        <goal>testCompile</goal>
      </goals>
      <configuration>
        <source>${testCompileSource}</source>
        <target>${testCompileSource}</target>
      </configuration>
    </execution>
  </executions>
</plugin>
...
<properties>
  <compileSource>1.4</compileSource>
  <testCompileSource>1.5</testCompileSource>
</properties>

如果您打算使用其他 编译器
,则涉及的更多。因为您需要指定JDK的路径以及所使用的编译器版本。同样,这些可以在属性中定义。尽管您可能想在settings.xml中定义它们

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <source>${compileSource}</source>
    <target>${compileSource}</target>
    <executable>${compileJdkPath}/bin/javac</executable>
    <compilerVersion>${compileSource}</compilerVersion>
  </configuration>
  <executions>
    <execution>
      <id>test-compile</id>
      <phase>process-test-sources</phase>
      <goals>
        <goal>testCompile</goal>
      </goals>
      <configuration>
        <source>${testCompileSource}</source>
        <target>${testCompileSource}</target>
        <executable>${testCompileJdkPath}/bin/javac</executable>
        <compilerVersion>${testCompileSource}</compilerVersion>
      </configuration>
    </execution>
  </executions>
</plugin>
...
<properties>
  <compileSource>1.4</compileSource>
  <testCompileSource>1.5</testCompileSource>
  <compileJdkPath>path/to/jdk</compileJdkPath>
  <testCompileJdkPath>path/to/test/jdk<testCompileJdkPath>
</properties>

注意,在配置文件中定义编译器配置可能是有意义的,对于您支持的每个JDK,一个配置文件都可以使用,以便您的常规构建不依赖于所设置的属性。

另外, 在Maven 3.x中,fork在指定可执行文件时需要包括参数,例如:

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <executions>
      <execution>
        <id>default-testCompile</id>
        <phase>test-compile</phase>
        <goals>
          <goal>testCompile</goal>
        </goals>
        <configuration>
          <fork>true</fork>
          <executable>${testCompileJdkPath}/bin/javac</executable>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>            
      </execution>
    </executions>
  </plugin>