Get Maven artifact version at runtime

Let’s imagine that we need to get the value of a certain Maven property in Java code. First, let’s create a text file with any name, for example version.txt in the src/main/resources folder:

project version is: ${project.version}

Now let’s add the following block to pom.xml:

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

Now, when building, Maven will replace the construction ${project.version} in the file with the real value of the variable.

Next, we need to make sure that the file is present on the final jar’s classpath. It remains to read it:

// Reads the version from the version.txt file, where maven writes the value when compiling
private String getVersion() {
  try {
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("version.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(Optional.ofNullable(inputStream).orElseThrow(IOException::new));
    try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
      return reader.readLine();
    } finally {
      inputStream.close();
      inputStreamReader.close();
    }
  } catch (IOException e) {
    log.error("Can't get version", e);
  }
  return "Unknown";
}

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

If I saved your day, you can support me :)

Leave a Reply

Your email address will not be published.