Maven Enforcer Plugin – Maven Enforcer 插件

最后修改: 2019年 2月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to learn about the Maven Enforcer Plugin and how we can use it to guarantee the level of compliance in our project.

在本教程中,我们将了解Maven Enforcer插件以及如何使用它来保证我们项目的合规性水平。

The plugin is especially handy when we have distributed teams, scattered across the globe.

当我们有分布在全球各地的团队时,这个插件特别方便。

2. Dependency

2.依赖性

To make use of the plugin in our project, we need to add the following dependency to our pom.xml:

为了在我们的项目中使用该插件,我们需要在我们的pom.xml中添加以下依赖性。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>3.0.0-M2</version>
</plugin>

The latest version of the plugin is available on Maven Central.

该插件的最新版本可在Maven Central上找到。

3. Plugin Configuration and Goals

3.插件配置和目标

Maven Enforcer has two goals: enforcer:enforce and enforcer:display-info.

Maven Enforcer有两个目标。enforcer:enforceenforcer:display-info

The enforce goal runs during a project build to execute rules specified in the configuration, while the display-info goal shows current information about the built-in rules that are present in the project’s pom.xml.

enforce目标在项目构建期间运行,以执行配置中指定的规则,而display-info目标则显示关于项目pom.xml中的内置规则的当前信息。

Let’s define the enforce goal in the executions tag. Furthermore, we’ll add the configuration tag that holds the rules definitions for the project:

让我们在executions标签中定义enforce目标。此外,我们将添加configuration标签,该标签持有项目的rules定义。

...
<executions>
    <execution>
        <id>enforce</id>
        <goals>
            <goal>enforce</goal>
        </goals>
        <configuration>
            <rules>
                <banDuplicatePomDependencyVersions/>
            </rules>
        </configuration>
    </execution>
</executions>
...

4. Maven Enforcer Rules

4.Maven执法者规则

The keyword enforce gives a subtle suggestion of the existence of rules to abide by. This is how the Maven Enforcer plugin works. We configure it with some rules that are to be enforced during the build phase of the project.

关键字enforce给出了一个微妙的暗示,即存在需要遵守的规则。这就是Maven Enforcer插件的工作原理。我们用一些规则来配置它,这些规则将在项目的构建阶段被强制执行。

In this section, we’re going to look at the available rules that we can apply to our projects to enhance their quality.

在这一节中,我们要看一下可用的规则,我们可以将其应用于我们的项目,以提高其质量。

4.1. Ban Duplicate Dependency

4.1.禁止重复的依赖性

In a multi-module project, where a parent-child relationship exists among POMs, ensuring there’s no duplicate of dependency in the effective final POM for a project can be a tricky task. But, with the banDuplicatePomDependencyVersions rule, we can easily make sure that our project is free of such glitch.

在一个多模块项目中,POM之间存在父子关系,确保项目的有效最终POM中没有重复的依赖关系是一项棘手的任务。但是,有了banDuplicatePomDependencyVersions规则,我们可以轻松地确保我们的项目没有这样的故障。

All we need to do is to add the banDuplicatePomDependencyVersions tag to the rules section of the plugin configuration:

我们需要做的就是在插件配置的rules部分添加banDuplicatePomDependencyVersions标签。

...
<rules>
    <banDuplicatePomDependencyVersions/>
</rules>
...

To check the rule’s behavior, we can duplicate one dependency in pom.xml and run mvn clean compile. It’ll produce the following error lines on the console:

为了检查规则的行为,我们可以在pom.xml中复制一个依赖,然后运行mvn clean compile。它将在控制台产生以下错误行。

...
[WARNING] Rule 0: org.apache.maven.plugins.enforcer.BanDuplicatePomDependencyVersions failed with message:
Found 1 duplicate dependency declaration in this project:
 - dependencies.dependency[io.vavr:vavr:jar] ( 2 times )

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.370 s
[INFO] Finished at: 2019-02-19T10:17:57+01:00
...

4.2. Require Maven and Java Version

4.2.需要Maven和Java版本

The requireMavenVersion and requireJavaVersion rules enable a project-wide lock-in of required Maven and Java versions, respectively. This will help eliminate the disparity that might arise from using different versions of Maven and JDK in development environments.

requireMavenVersionrequireJavaVersion规则分别实现了项目范围内对所需Maven和Java版本的锁定。这将有助于消除开发环境中使用不同版本的Maven和JDK可能产生的差异。

Let’s update the rules section of the plugin configuration:

让我们更新一下插件配置中的rules部分。

<requireMavenVersion>
    <version>3.0</version>
</requireMavenVersion>
<requireJavaVersion>
    <version>1.8</version>
</requireJavaVersion>

These allow us to specify the version numbers in a flexible manner, as long as they comply with the plugin’s version range specification pattern.

这些允许我们以灵活的方式指定版本号,只要它们符合插件的版本范围规范模式即可。

Furthermore, both rules also accept a message parameter for specifying a custom message:

此外,这两条规则还接受一个message参数,用于指定一个自定义的消息。

...
<requireMavenVersion>
    <version>3.0</version>
    <message>Invalid Maven version. It should, at least, be 3.0</message>
</requireMavenVersion>
...

4.3. Require Environment Variable

4.3.要求环境变量

With the requireEnvironmentVariable rule, we can ensure that a certain environment variable is set in the execution environment.

通过requireEnvironmentVariable规则,我们可以确保执行环境中设置了某个环境变量。

It can be repeated to accommodate more than one required variable:

它可以重复进行,以适应一个以上的所需变量。

<requireEnvironmentVariable>
    <variableName>ui</variableName>
</requireEnvironmentVariable>
<requireEnvironmentVariable>
    <variableName>cook</variableName>
</requireEnvironmentVariable>

4.4. Require Active Profile

4.4.要求活动档案

Profiles in Maven help us to configure properties that’ll be active when our application is deployed to different environments.

Maven中的Profiles帮助我们配置属性,当我们的应用部署到不同的环境中时,这些属性将是有效的。

Consequently, we can use the requireActiveProfile rule when we need to ensure that one or more specified profiles are active, thus guaranteeing the successful execution of our application:

因此,当我们需要确保一个或多个指定的配置文件处于活动状态时,我们可以使用requireActiveProfile规则,从而保证我们应用程序的成功执行。

<requireActiveProfile>
    <profiles>local,base</profiles>
    <message>Missing active profiles</message>
</requireActiveProfile>

In the snippet above, we used the message property to provide a custom message to show if the rule-check fails.

在上面的片段中,我们使用message属性来提供一个自定义消息,以便在规则检查失败时显示。

4.5. Other Rules

4.5.其他规则

The Maven Enforcer plugin has many other rules to promote project quality and consistency irrespective of the development environment.

Maven Enforcer插件有许多其他规则,以促进项目质量和一致性,而不论开发环境如何。

Also, the plugin has a command to display info about some currently configured rules:

另外,该插件有一个命令,可以显示当前配置的一些规则的信息。

mvn enforcer:display-info

5. Custom Rules

5.自定义规则

So far, we’ve been exploring the built-in rules of the plugin. Now, it’s time to look at creating our own custom rule.

到目前为止,我们一直在探索该插件的内置规则。现在,是时候看看如何创建我们自己的自定义规则了。

First, we need to create a new Java project that’ll contain our custom rule. A custom rule is a class Object that implements the EnforceRule interface and overrides the execute() method:

首先,我们需要创建一个新的Java项目,它将包含我们的自定义规则。自定义规则是一个Object类,实现了EnforceRule接口并重写了execute() 方法

public void execute(EnforcerRuleHelper enforcerRuleHelper) throws EnforcerRuleException {
    try {
        String groupId = (String) enforcerRuleHelper.evaluate("${project.groupId}");
        if (groupId == null || !groupId.startsWith("com.baeldung")) {
            throw new EnforcerRuleException("Project group id does not start with com.baeldung");
        }
    }
    catch (ExpressionEvaluationException ex) {
        throw new EnforcerRuleException( "Unable to lookup an expression " 
          + ex.getLocalizedMessage(), ex );
    }
}

Our custom rule simply checks if the target project’s groupId starts with com.baeldung or not.

我们的自定义规则只是检查目标项目的groupId是否以com.baeldung开头。

Notice how we don’t have to return boolean or anything as such to indicate the rule is not satisfied. We just throw an EnforcerRuleException with a description of what is wrong.

请注意,我们不需要返回boolean或任何类似的东西来表明规则不被满足。我们只是抛出一个EnforcerRuleException,并描述了问题所在。

We can use our custom rule by adding it as a dependency to the Maven Enforcer plugin:

我们可以通过将我们的自定义规则作为Maven Enforcer插件的依赖项来使用它

...
<rules>
    <myCustomRule implementation="com.baeldung.enforcer.MyCustomRule"/>
</rules>
...

Please note that if the custom rule project is not a published artifact on Maven Central, we can install it into the local Maven repo by running the mvn clean install.

请注意,如果自定义规则项目不是Maven Central上发布的工件,我们可以通过运行mvn clean install.将其安装到本地Maven repo。

This will make it available when compiling the target project that has the Maven Enforcer Plugin. Please see the plugin’s documentation for the custom rule to learn more.

这将使其在编译拥有Maven Enforcer插件的目标项目时可用。请参阅该插件的自定义规则的文档以了解更多信息。

To see it in action, we can set the groupId property of the project with the Enforcer Plugin to anything other than “com.baeldung” and run mvn clean compile.

为了看到它的作用,我们可以将带有Enforcer插件的项目的groupId属性设置为 “com.baeldung “以外的任何内容,然后运行mvn clean compile

6. Conclusion

6.结论

In this quick tutorial, we saw how the Maven Enforcer Plugin can be a useful addition to our existing chest of plugins. The ability to write custom rules enhance its range of application.

在这个快速教程中,我们看到了Maven Enforcer插件是如何成为我们现有插件库中的一个有益补充。编写自定义规则的能力增强了其应用范围。

Please note that we need to uncomment the dependencies and rule for the custom-rule example in the complete example source code that’s available over on GitHub.

请注意,我们需要在GitHub上提供的完整示例源代码中取消对自定义规则示例的依赖关系和规则的注释,