Sometimes, it’s useful to display the project version in your application. That version can be found in the MANIFEST.MF file. It’s located in every JAR or WAR file in the META-INF folder.
example.war -> META-INF -> MANIFEST.MF
If you open that file, you can see some project information. We need to get the Implementation-Version. Here is an example of a MANIFEST.MF file
1 2 3 4 5 6 7 8 9 |
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: hudson Build-Jdk: 1.6.0_27 Hudson-Build-Number: 667 Hudson-Project: example Hudson-Version: 1.400 Implementation-Version: 2.3.1-SNAPSHOT |
To get that version I’ll give you a class ManifestInfo.java. The ‘getVersion’ method gives you that implementation-version. Don’t forget to init the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.laurenthinoul.webapp; import java.io.IOException; import java.util.Properties; import javax.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.ServletContextAware; public class ManifestInfo implements ServletContextAware { private static final String VERSION_ROW = "Implementation-Version"; private static final String MANIFEST_NAME = "/META-INF/MANIFEST.MF"; private static final Properties MANIFESTINFO = new Properties(); private static ServletContext servletContext; private static final Logger LOGGER = LoggerFactory.getLogger(ManifestInfo.class); private static void setContext(ServletContext servletContext) { ManifestInfo.servletContext = servletContext; } public void init() { final String name = MANIFEST_NAME; try { ManifestInfo.MANIFESTINFO.load(servletContext.getResourceAsStream(name)); } catch (final IOException e) { LOGGER.warn(e.getMessage()); } catch (final NullPointerException e) { LOGGER.warn(e.getMessage()); } } public String getVersion() { return (String) ManifestInfo.MANIFESTINFO.get(VERSION_ROW); } @Override public void setServletContext(ServletContext servletContext) { ManifestInfo.setContext(servletContext); } } |
When you use Spring, you need to add the line below:
1 |
<bean id="manifestInfo" class="com.laurenthinoul.webapp.ManifestInfo" init-method="init" /> |
Hope this works for you, enjoy!
1 comment for “How to display project version in Java”