2

I have a Java 11 application which I develop using Maven and in the pom.xml I have a version declared.

<groupId>my.group.id</groupId>
<artifactId>artifact</artifactId>
<version>0.1.2.3</version>

I want to get this version at runtime e.g. using getClass().getPackage().getImplementationVersion() as it's described in this question. This works as long as I don't package my application as a modular runtime image using Jlink. Then I only get null returned from above call.

I package my application using:

jlink --output target/artifact-image --module-path target/dependencies --launcher MyApp=my.module.name/my.main.Class --add-modules my.module.name

Jlink has actually a parameter --version but this returns the Jlink version instead setting it for the generated artifact.

So, how can I get the version (of my Maven project) at runtime?

  • How to define it in the modular application?
  • How to get it into the modular application?
  • How to read it in the modular application?

I know I could define it in a resource file and simply read it from there, however I prefer to have it only in the pom.xml (= to have a single source of truth).

Itchy
  • 2,003
  • 23
  • 36

1 Answers1

0

In the end I did this using the filtering function of the Maven Resources Plugin.

First, enable filtering in the pom.xml:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

Then add a src/main/resources/my-version.properties file containig:

my.version=${project.version}

So you can use the following code in Java:

Properties myProperties = new Properties();
try {
    myProperties.load(getClass().getResourceAsStream("/my-version.properties"));
} catch (IOException e) {
    throw new IllegalStateException(e);
}
String theVersion = Objects.requireNonNull((String) myProperties.get("my.version"));
Itchy
  • 2,003
  • 23
  • 36