My solution for the standard Maven WAR plugin
Add a resources tag to you build section which enables filtering (aka "search and replace"):
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
....
<build>
Then in your src/main/resources add a version.properties file containing any filter variables that matches one of the standard maven build variables (you can also use filtering feature to load your own custom variables):
pom.version=${pom.version}
Now when you do a "maven package" or a maven install it will copy the version.properties file into the WEB-INF/classes and do a search and replace to add the pom version into the file.
To get at this with Java use a class such as:
public class PomVersion {
final private static Logger LOGGER = LogManager.getLogger(PomVersion.class);
final static String VERSION = loadVersion();
private static String loadVersion() {
Properties properties = new Properties();
try {
InputStream inStream = PomVersion.class.getClassLoader().getResourceAsStream("version.properties");
properties.load(inStream);
} catch (Exception e){
LOGGER.warn("Unable to load version.properties using PomVersion.class.getClassLoader().getResourceAsStream(...)", e);
}
return properties.getProperty("pom.version");
}
public static String getVersion(){
return VERSION;
}
}
Now you can just call PomVersion.getVersion() to put the version number of the pom file into the page. You can also have the WAR file be given the same number by using a filter variable in the finalName within the pom.xml:
<build>
<finalName>my-killer-app-${pom.version}</finalName>
...
</build>
so now if you set your application version in your pom to be 01.02.879:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.killer.app</groupId>
<artifactId>my-killer-app</artifactId>
<packaging>war</packaging>
<name>This App Will Rule The World</name>
<version>01.02.879</version>
...
</project>
when you do an "mvn install" the war file name include the version number also:
my-killer-app-01.02.879.war
finally if you use Spring heavily such as with SpringMVC/SpringWebFlow you can make a singleton service bean which uses that class to avoid having to reference the low level class by name:
@Service("applicationVersion")
public class ApplicationVersion {
final static String VERSION = PomVersion.getVersion();
public String getVersion() {
return VERSION;
}
}