Nov 1, 2018

How to Compile Sources Using A Different JDK in Maven

Compiling Sources Using A Different JDK

The compilerVersion parameter can be used to specify the version of the compiler that the plugin will use. However, you also need to set fork to true for this to work. For example:
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <verbose>true</verbose>
          <fork>true</fork>
          <executable><!-- path-to-javac --></executable>
          <compilerVersion>1.8</compilerVersion>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>
To avoid hard-coding a filesystem path for the executable, you can use a property. For example:
<executable>${JAVA_8_HOME}/bin/javac</executable>
Each developer then defines this property in settings.xml, or sets an environment variable, so that the build remains portable.