Reading the POM version in a web application
Sometimes you need to get the version of your application in the Java code. Setting a constant manually is an extra step in the release process and will probably be forgotten in some releases.
But there is a simple way if you are using Maven: You can tell the war plugin to put the application version into the MANIFEST.MF file. From there you can read it in your Java code. Here is an example for configuring the plugin:
<plugin>
<groupId>org.apache.maven.plugins<groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
The important part is to configure the plugin with the addDefaultImplementationEntries directive. This will tell it to put the version, among other things, in the MANIFEST.MF file.
Then we read the version in the Java code. Below is a simple example:
ServletContext servletContext = getServletContext();
InputStream inputStream = servletContext.getResourceAsStream(“/META-INF/MANIFEST.MF”);
Manifest manifest = new Manifest(inputStream);
String applicationVersion = manifest.getMainAttributes().getValue(“Implementation-Version”);
The getServletContext() method should be replaced with the regular way of getting the servlet context in the web framework you use. And the example lacks try-catch and closing of the inputStream.