Monday, June 25, 2007

Profiles + Dependency Management

The problem:

You want to be able to easily switch between versions of dependencies in your project. This could be in the range of only one project dependency up to every dependency in you project.

The solution:

You can create profiles that each define a dependency management section. In each of these dependency management sections you can set the versions for dependencies in your project. Then you will invoke a profile to set the dependency (or dependencies) version(s) used in building, testing, releasing etc.

Now why would you want to do this? Well there are a set of situations where you need your project to be able to build and release in lieu of differing version requirements. You may be building a framework that should work with Spring 1.x and Spring 2.x, or maybe Servlet spec 2.4 and 1.x. Let's look at such an example to demonstrate this technique:

<profiles>
<profile>
<id>newspring</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupdId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.1</version>
</dependency>
<dependencies>
</dependencyManagement>
</profile>
<profile>
<id>oldspring</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupdId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>1.2.1</version>
</dependency>
<dependencies>
</dependencyManagement>
</profile>
</profiles>


In the above example you can see that you could specify the "newspring" profile to use Spring version 2.1, or the profile "oldspring" to use 1.2. You can apply other profile techniques such as default profiles here. Where can you define configuration such as the above? Well normally you would put it directly into your pom.xml. Doing so allows you you to leverage the parent child relationship! You can create profiles which contain different dependency versions in dependency management sections, and inherit them by many child projects. This allows child projects to easily specify which versions of certain technologies are used (I need to create a lengthy example of this in action!).

FYI, you likely will not use this technique in a simple Maven project, rather it will be used with some other advanced techniques.