How to get the value of the version property in pom.xml?

2

I need to get the value of the current version of the application in various parts of the code. A priori I thought about creating a class containing the version:

public class Version {
    public static String getVersion(){
        return "0.1.0";
    }
}

But there must be a better way to do this (I believe).

I've seen that Java has a versioning specification , but I do not understand if it's for the same purpose I'm looking for.

Well, as I'm using Maven and there is the <version> property in the configuration file, I thought it would be easier to update this property at the time of maintenance, just use this property throughout the project.

The question is: Is it possible to get this property? If so, how to do it?
If not, could you give me alternatives?

    
asked by anonymous 02.12.2015 / 06:36

1 answer

1

The Maven Resources Plugin allows you to perform maven variable substitutions in files ( resources ) of the project.

This plugin is part of maven's default execution plan for process-resources and process-test-resources phases, so you need to instruct the plugin to replace variables during these phases.

Following the documentation example, you simply need to add the following configuration:

<project>
  ...
  <name>My Resources Plugin Practice Project</name>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
      ...
    </resources>
    ...
  </build>
  ...
</project>

Then any file in the specified directory will be processed by Maven. You could then create a txt or properties containing the version:

versao=${project.version}

In this way, Maven will take care of placing the correct version when packaging the project.

If there are other files in the project it may be best to avoid them being unnecessarily or improperly processed. You can specify multiple <resource> tags containing <include> and <exclude> tags to specify which files to process and which ones to remain intact.

Example:

<project>
  ...
  <build>
    ...
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/*.properties</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>false</filtering>
        <excludes>
          <exclude>**/*.properties</exclude>
        </excludes>
      </resource>
      ...
    </resources>
    ...
  </build>
  ...
</project>
    
02.12.2015 / 07:16