Generate and display Maven Build timestamp in WAR

On all the pages of my webapp I want to see when the WAR was built (i.e. a build timestamp). Here is how I did it:

Add this to the pom.xml of your webapp module:

<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
</build> 

<properties>
  <mavenBuildTimestamp>${maven.build.timestamp}</mavenBuildTimestamp>
</properties>

Create a file src/main/resources/build.properties in  in your webapp module with the following content:

# Build Time Information
build.timestamp=${mavenBuildTimestamp}

The Maven build will replace the Maven property and the resulting file WEB-INF/classes/build.properties will look like this:

# Build Time Information
build.timestamp=20101016-0303

Now we just need a Spring PropertiesFactoryBean definition to make properties available at runtime:

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:build.properties</value>
    </list>
  </property>
</bean>

I used a simple Spring bean to make the timestamp easily available in Spring Web Flow / Spring Faces EL expressions:

@Component
public class ViewUtil {

  private Properties appProperties;

  /**
   * @param appProperties Global Application properties
   */
  @Resource
  public void setAppProperties(Properties appProperties) {
    this.appProperties = appProperties;
  }

  /**
   * @return The Build Timestamp as generated by Maven
   */
  public String getBuildTimestamp() {
    return appProperties.getProperty("build.timestamp", "UNKNOWN");
  }
}

The EL expression code in the JSF page is then something like this:

Build timestamp: #{viewUtil.buildTimestamp} 

And this is what the result looks like on the page:

Build Timestamp screenshot

If you want to be able to refer to properties directly by name in your Spring configuration you can define a Spring PropertyPlaceholderConfigurer:

<bean id="propertyConfigurer"
      class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
  <property name="properties" ref="appProperties" />
</bean>

2 thoughts on “Generate and display Maven Build timestamp in WAR

  1. Very well written Oliver. I’d like to familiarize myself with Maven. We use Ant and SVN. Can you suggest some good examples/starting point? So many examples are available but many expect a little background in Maven. I don’t have any prior experience with it.

    Thanks,

    Mike.

Leave a reply to mollix Cancel reply