如何配置maven编译插件的JDK版本.md 2.6 KB

普通maven项目配置编译器版本

参考maven官方文档 Setting the -source and -target of the Java Compiler

maven有2种方法设置编译JDK版本,比如配置为 Java 1.8 版本

  1. 配置属性
<project>
  [...]
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  [...]
</project>
  1. 直接配置插件
<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

如果在IDEA里正确设置了JDK版本,但不生效,右键 pom.xml ,选择Maven,点击 Reimport

source属性说明:

The -source argument for the Java compiler.

NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6. Since 3.9.0 the default value has changed from 1.6 to 1.7 Default value is: 1.7. User property is: maven.compiler.source.

target属性说明:

The -target argument for the Java compiler.

NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6. Since 3.9.0 the default value has changed from 1.6 to 1.7 Default value is: 1.7. User property is: maven.compiler.target.

从 maven-compiler-plugin3.8.0 开始,默认java编译器版本由1.5改为1.6了 从 maven-compiler-plugin3.9.0 开始,默认java编译器版本由1.6改为1.7了

更多属性说明参见maven-compiler-plugin

SpringBoot项目配置maven编译器版本

如果引用做了父项目,可以如下配置

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 配置java编译器版本 -->
<properties>
    <java.version>1.8</java.version>
</properties>

配置及其简单,因为在 spring-boot-starter-parent 已经配置好了 source、target 属性,只需用 java.version 覆盖默认值即可

<properties>
    [...]
    <java.version>1.8</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    [...]
</properties>