在 Java 8 上安装和编译 Maven 工件

Installing and compiling Maven artifacts on Java 8

我有一个带有 pom.xml 的项目,该项目具有以下 <build> 声明:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

当我 运行 mvn install 在这个项目上时,它编译项目,运行s 单元测试并将它发布到我的本地 repo。我想在这里学习更多关于 Maven 的知识,但很难找到 documentation/explanations 以下内容:

首先你应该了解构建生命周期是什么,它是如何工作的,以及插件是如何工作的are bound to the life cycle by default

此外,您应该了解,在 Maven 中,每个项目都继承自 super pom 文件,该文件是 Maven 分发版(您下载的包)的一部分。 super pom 定义了默认的文件夹布局和一些版本的插件。

像您那样定义 maven-compiler-plugin 的问题是非常准确,但完全错误。您应该像下面这样定义它:

<build>
  <pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
  </pluginManagement>
</build>

这将覆盖由 super pom 继承的定义并更改其配置。在您的情况下,我建议将定义更改为:

  <project>
    ...
    <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
      <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
      </pluginManagement>
    </build>
    ..
  </project>

应该全局设置编码,因为还有其他插件使用此定义,如 maven-resources-plugin。上面 属性 的用法简化了这一点,因为每个有编码选项的插件都将使用 default as defined in the property.

为了确保使用正确版本的 Java(您的机器上的 JDK),您必须使用 maven-enforcer-plugin.

除此之外,请查看 plugins page which shows the most up-to-date releases of the plugins

作为一个很好的文档,我可以推荐 Books on Maven 但请注意它们是用 Maven 2 编写的。因此,如果不清楚,请在 SO 上的用户邮件列表中询问。