20. July 2010

Display Maven artifact versions in JSF pages

I was recently confronted with the task of displaying the version of a JSF project in its page title. As the version was already contained in the project's pom.xml and I didn't want to duplicate this information in another file, I searched for a simple way to display the Maven artifact's version in the JSF page.

As there was no easy way to do this, I created a small library for this usecase and named it jsf-maven-util. The main idea of it is to supply a JSF managed bean that lazily checks for pom.properties files of Maven artifacts on the classpath. These files are created during the Maven packaging process and are stored in the META-INF/maven/ directory of the output archive.

The library is very easy to use. A bean named maven is automatically placed in the application scope of your webapp. It contains a map which you can use to get the version of an artifact by using the groupId and artifactId (colon-separated) as the key.

This example shows how to display the version of a web application in its page title.

<head>
  <title>
    My Application #{maven.version['com.example.myapp:myapp-webapp']}
  </title>
</head>  

You can also display the version of any of your project's dependencies as long as it includes a pom.properties in its archive:

<p>
  powered by Weld #{maven.version['org.jboss.weld:weld-core']}  
</p>

If you are interested in using this feature in your own project, add the following repository to your pom.xml:

<repository>
  <id>jsf-maven-util-repo</id>
  <name>jsf-maven-util Repository</name>
  <url>http://chkal.github.com/jsf-maven-util/repository/</url>
</repository>

Then add the following dependency to your project:

<dependency>
  <groupId>de.chkal.jsf</groupId>
  <artifactId>jsf-maven-util</artifactId>
  <version>1.1</version>
</dependency>

I pushed the source to a GitHub repository. Let me know if you have any issues.