Java - In App version with Maven
Intro
In this post I will show you an easy alternative how to use Maven’s resource filter feature and combine it with some portions of Java code in order to make the build version available to the app at runtime.
Thinking further when it comes to continuous integration the Maven build version may be set by the CI Server via the Maven version plugin where a unique build number may be part of the same. Or such build number could be set over an additional Java argument as part of the Maven build command where we would need to introduce a separate property placeholder within our version property file - this to be explained more in detail in a follow-up post.
Basic Setup
- The following code snippet demonstrates how to easily read properties from file over the java.util.ResourceBundle:
- Placing a simple properties file located on the class path (e.g.
/src/main/resources-filtered/ch/mycompany/myapp/version.properties) containing some key/values where the values can be filtered via maven (placeholders) during the build process will make the same available to the app at runtime:
- More in detail, passing the resource bundle locator to the code snippet as seen above during initialization will read the properties:
- Assuming maven as the build tool, we can add the following properties to the project POM in order to let maven generate a build timestamp that can be consumed as property:
- After successful maven build completion the properties file may look as follows (sample):