用于test和main的不同maven编译器版本
-
06-07-2019 - |
题
如何配置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>
其他提示
我对使用 maven-compiler-plugin
版本3.5.1编译java 7源代码和java 8测试源的已接受答案没有运气。因为compile插件使用了main和test源的源/目标参数。
但我发现,测试源和目标有单独的配置参数。
对我来说,有效的解决方案是
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<testSource>1.8</testSource>
<testTarget>1.8</testTarget>
</configuration>
</plugin>
</plugins>
</build>
不隶属于 StackOverflow