Maven 中设置工程的语言编译级别(compiler level)

Maven 工程缺省的情况下,它的编译级别(compiler level)是 JDK 1.5 这一级。对于现在的许多项目而言,这已经太老了,很多特性也不支持,所以,我们通常需要定义自己所需要的语言级别。

具体而言,有两种方式,一是添加两个属性值,另外是配置 compiler plugin,详细参考:http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html

设置属性值

在 pom.xml 的 properties 标签中加入以下属性值:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<!-- ... 其它配置略 -->

	<properties>
          <maven.compiler.source>1.8</maven.compiler.source>
          <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
</project>

设置 compiler plugin

如果上述设置在某些情况下还不行,则也可以通过设置 compiler plugin 来实现,这点可以通过在 pom.xml 文件的 build 节点下的 plugins 节点下面增加一个 maven-compiler-plugin 来实现,具体如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<!-- ... 其它配置略 -->

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
以上配置将语言级别设置为 Java 1.8,你也可以根据需要设为 1.7 或 1.6.
之后,在工程下:右键--maven--update project 来重新编译整个项目。(适用于 Eclipse)