Java
Maven
Artifact Version
Runtime
Dependency Management

Get Maven artifact version at runtime

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In a Java project, Maven is a widely-used build automation tool that simplifies project management by handling dependencies, compiling code, running tests, and packaging the code. However, there are scenarios where you need to know the version of your Maven artifact at runtime. This knowledge can be crucial for operational logging, debugging, or conditional logic based on different versions.

Introduction to Maven Artifact Versioning

Maven artifacts are deployed to repositories with a specific version, usually specified in the pom.xml file. It's important to track the version for deploying or troubleshooting software across environments. Although Maven manages versions during build time, getting the artifact version at runtime requires some additional steps.

Fetching the Maven Artifact Version at Runtime

Method 1: Using the getClass().getPackage()

Java provides methods to retrieve package information for a class, which typically includes version information if the manifest file in the JAR includes this data.

java
1public class VersionUtil {
2    public static void main(String[] args) {
3        Package pkg = VersionUtil.class.getPackage();
4        String version = pkg.getImplementationVersion();
5        System.out.println("Artifact version: " + version);
6    }
7}

Explanation

  • The getImplementationVersion() method retrieves the implementation version from the JAR’s manifest file.
  • This requires the JAR to be packaged with these attributes in its manifest, populated typically by the Maven jar plugin during the build process.

Method 2: Reading from META-INF/MANIFEST.MF

If your JAR includes a manifest file with version information, you can directly read it.

java
1import java.io.IOException;
2import java.io.InputStream;
3import java.util.jar.Attributes;
4import java.util.jar.Manifest;
5
6public class VersionManifestReader {
7    public static void main(String[] args) {
8        try (InputStream inputStream = VersionManifestReader.class.getResourceAsStream("/META-INF/MANIFEST.MF")) {
9            if (inputStream != null) {
10                Manifest manifest = new Manifest(inputStream);
11                Attributes attributes = manifest.getMainAttributes();
12                String version = attributes.getValue("Implementation-Version");
13                System.out.println("Artifact version: " + version);
14            }
15        } catch (IOException e) {
16            e.printStackTrace();
17        }
18    }
19}

Explanation

  • This method opens the manifest file directly using class resources.
  • The Implementation-Version attribute is read from the manifest. This key is standard when using Maven's JAR plugin to include versioning information.

Method 3: Using the Maven Plugins

maven-resources-plugin

The Maven Resources Plugin can filter resource files, which allows embedding version information within various configuration files or code files during the build.

  1. Add the filter resource to your pom.xml:
xml
1    <build>
2      <resources>
3        <resource>
4          <directory>src/main/resources</directory>
5          <filtering>true</filtering>
6        </resource>
7      </resources>
8      <plugins>
9        <plugin>
10          <groupId>org.apache.maven.plugins</groupId>
11          <artifactId>maven-resources-plugin</artifactId>
12          <version>3.2.0</version>
13        </plugin>
14      </plugins>
15    </build>
  1. Define properties in the pom.xml:
xml
    <properties>
      <version>${project.version}</version>
    </properties>
  1. Access the version within your application:
properties
    # application.properties
    application.version=@version@

Method 4: Embedding Using Java Annotations

Sometimes you might want to use Java annotations in conjunction with resource filtering to bring about compile-time annotations that can access build-time properties.

java
1@Retention(RetentionPolicy.RUNTIME)
2@Target(ElementType.TYPE)
3public @interface BuildInfo {
4    String version();
5}
6
7// Usage
8@BuildInfo(version = "@version@")
9public class MyApp {
10    public static void main(String[] args) {
11        BuildInfo buildInfo = MyApp.class.getAnnotation(BuildInfo.class);
12        System.out.println("Artifact version: " + buildInfo.version());
13    }
14}

Key Points Table

MethodRequirementsProsCons
getClass().getPackage()Package JAR with Implementation-Version in manifestSimple and built-inDepends on manifest
Reading from ManifestPackaged JAR with available manifestDirect access to version infoRequires I/O operations
Maven Resources PluginConfigure filtering in pom.xml and use properties fileFlexible and configurable approachRequires build setup
Java Annotations & FilteringAnnotations and filtered valuesCompile-time constant accessCompile-time setup required

Additional Considerations

  • Build Automation: Automating the inclusion of version information in builds can help maintain consistency.
  • Operational Logging: Consider logging version information in application startup logs.
  • Conditional Logic: Use runtime version checking in cases where code behavior alters based on version changes.

Conclusion

Fetching the Maven artifact version at runtime is a versatile skill that can improve application management and deployment processes. Whether through manifest reading, Java annotations, or Maven plugins, each method offers unique advantages depending on the build requirements and resources.


Course illustration
Course illustration

All Rights Reserved.