Tuesday, October 06, 2015

Automating dependency versions in Maven

Reading the most excellent Modern Java series of posts, I realized I could automate a command line step I always did manually—updating dependency versions:

$ mvn versions:update-properties

I can automate that! The simplest possible POM demonstrating:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>example-group</groupId>
    <artifactId>example-artifact</artifactId>
    <version>0-SNAPSHOT</version>

    <properties>
        <example-dependency.version>1</example-dependency.version>
        <generateBackupPoms>false</generateBackupPoms>
        <versions-maven-plugin.version>2.2</versions-maven-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>example-group</groupId>
            <artifactId>example-dependency</artifactId>
            <version>${example-dependency.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>${versions-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>update-dependencies</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>update-properties</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

My hypothetical maven build says:

$ mvn clean
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building example-artifact 0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ example-artifact ---
[INFO]
[INFO] --- versions-maven-plugin:2.2:update-properties (update-dependencies) @ example-artifact ---
[INFO] Property ${example-dependency.version}: Leaving unchanged as 1.2.3
[INFO] Property ${versions-maven-plugin.version}: Leaving unchanged as 2.2

The key is using <phase>validate</phase> in the plugin execution. The first lifecycle phase for maven is "validate". Setting the property "generateBackupPoms" to "false" prevents pom.xml.versionsBackup files from littering the project. You are using source control, aren't you?

Update

This approach is best during development, especially for greenfield projects. I would not recommend it for stable or legacy projects where dependency versions need to be kept constant.

No comments: