0

I have a project with a pom.xml that has the following <build> declaration:

<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>

When I run mvn install on this project, it compiles the project, runs unit tests and publishes it to my local repo. I am trying to learn a little more about Maven here, and am having a tough time finding documentation/explanations on the following:

  • How am I able to run mvn install, if the POM doesn't declare it under build/plugins? Does maven-compiler-plugin include maven-install-plugin, if so, how could I have figured that out?
  • Most importantly: the value of build/plugins/plugin/configuration/source and .../target are both set to 1.8. If my machine has Java 8 on it, and I run mvn install on this project without any errors, does that guarantee that the project builds with Java 8? I'm looking at the docs for the Compiler Plugin and don't see those source/target configs listed anywhere.
4

1 回答 1

4

首先,您应该了解构建生命周期是什么,它是如何工作的,以及插件是如何默认绑定到生命周期的

此外,您应该了解,在 Maven 中,每个项目都继承自超级 pom文件,该文件是 maven 发行版(您下载的包)的一部分。超级 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>

这将覆盖由超级 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. 上述属性的使用简化了这一点,因为每个具有编码选项的插件都将使用属性中定义的默认值

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

除此之外,请查看插件页面,该页面显示插件的最新版本

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

于 2015-03-13T15:15:56.473 回答