Maven: how to put in a Java source the project version defined in pom.xml

Abubusoft Blog

Maven: how to put in a Java source the project version defined in pom.xml

Recently I decided to insert a message during Kripton Persistence Library initialization at run-time which display library version. To accomplish this task I need to include in the source code the maven project version contained in pom.xml. Is there a plugin for maven that can help me? The answer is YES! It’s templating-maven-plugin. So, I modified my pom.xml to include the plugin:

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

	<parent>
		<groupId>com.abubusoft</groupId>
		<artifactId>kripton-parent</artifactId>
		<version>7.0.0-rc.4</version>
		<relativePath>../kripton-parent/pom.xml</relativePath>
	</parent>

	<artifactId>kripton-core</artifactId>
	<name>Kripton Core</name>
	<packaging>jar</packaging>
	<description>Kripton Persistence Library - core module </description>

	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>templating-maven-plugin</artifactId>
				<version>1.0.0</version>
				<executions>
					<execution>
						<id>filtering-java-templates</id>
						<goals>
							<goal>filter-sources</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>

Then, I create java-template directory under folder src/main/ and I wrote the KriptonVersion class:

package com.abubusoft.kripton;

public final class KriptonVersion {
	public static final String VERSION = "${project.version}";
}

An image is better than a thousand of words:

An exampe to how to modify the maven project to use project version at run-time

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *