Java Maven编译版本的坑

2017/05/03 Java

Java 编译版本的坑

Maven中可以指定JDK,如下:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
</build>

这种情况下,看起来代码是用JDK1.7版本编译的了,但是Maven 官方给了一个说明,说这种情况不能保证一定可以用于target版本所指的JRE使用,所以如果要发布最好的选择还是选择和发布环境相同的JDK版本来打包。 官方的英文原谅解释如下:

Merely setting the target option does not guarantee that your code actually runs on a JRE with the specified version. The pitfall is unintended usage of APIs that only exist in later JREs which would make your code fail at runtime with a linkage error. To avoid this issue, you can either configure the compiler’s boot classpath to match the target JRE or use the Animal Sniffer Maven Plugin to verify your code doesn’t use unintended APIs. In the same way, setting the source option does not guarantee that your code actually compiles on a JDK with the specified version. To compile your code with a specific JDK version, different than the one used to launch Maven, refer to the Compile Using A Different JDK example.

对此,我的感想是软件果然是不靠谱的。

正确的做法

<plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <verbose>true</verbose>
          <fork>true</fork>
          <executable><!-- path-to-javac --></executable>
          <compilerVersion>1.7</compilerVersion>
        </configuration>
      </plugin>
</plugins>

为了不硬编码在POM.xml文件中,可以在Maven的Settings.xml文件中指定属性。如下:

<profiles>
    [...]
    <profile>
      <id>compiler</id>
        <properties>
          <JAVA_1.7_HOME><!-- somePath --></JAVA_1.7_HOME>
        </properties>
    </profile>
  </profiles>

事实近一步证明了CI服务器是多么的重要。

Show Disqus Comments

Search

    Table of Contents