Controlling the constraints

One of the requirements for a build tool is to be able to generate repeatable builds. In a project, the build tool should behave identically for all team members. While a project guideline can be made on the version of Java or Maven to be used, it would be easier if it could be enforced automatically.

This is where the Maven Enforcer plugin comes in.

How to do it...

  1. Open a simple project (project-with-enforcer).
  2. Add the following plugin configuration:
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-enforcer-plugin</artifactId>
            <version>1.3.1</version>
            <executions>
              <execution>
                <id>enforce-versions</id>
                <goals>
                  <goal>enforce</goal>
                </goals>
                <configuration>
                  <rules>
                    <requireMavenVersion>
                      <version>3.2.3</version>
                    </requireMavenVersion>
                    <requireJavaVersion>
                      <version>1.8</version>
                    </requireJavaVersion>
                  </rules>
                </configuration>
              </execution>
            </executions>
          </plugin>
  3. Build the project using Java 7 and Maven 3.2.3:
    mvn clean package.
    
  4. Observe the output:
    How to do it...

How it works...

The Enforcer plugin uses the rules configuration and validates the project against the rules. If it finds violations, it reports the error(s) and does not proceed with the build.

In the preceding example, our project had two issues:

  • The Maven version: We were using version 3.2.3 but we had specified 3.2.5 in the rules
  • The Java version: We were using Java 7 but we had specified Java 8 in the rules

There's more...

The Maven Enforcer plugin has several other rules to enforce various constraints. A couple of them are as follows:

  • requireOS: This ensures the project can be built only on specific operating systems
  • requireFilesExist: This ensures specific files exist for the project to build

It is also possible to implement custom enforcer rules. One such is available at https://github.com/ferstl/pedantic-pom-enforcers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.166.131