Monday, June 4, 2007

Profiles in Maven

The problem:

You would like to set up Maven to run in one or more configurations that you have defined.

The solution:

Maven has a profile mechanism that naturally fits this type of thing. You can create any number of profiles that each contain settings that can override other Maven settings. Here is an example of some profiles:


<profiles>
<!-- profile for java 5 -->
<profile>
<id>java5</id>
<activation>
<property>
<name>jdk</name>
<value>5</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<!-- profile for java 6 -->
<profile>
<id>java6</id>
<activation>
<property>
<name>jdk</name>
<value>6</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>


Name this profiles.xml and put it into your projects folder next to the pom.xml. You may have noticed the activation elements in the file. These are what trigger the profile to be active. You can trigger these by defining a system property with the value given in the activation value element. So you use Java 6 compilation you would do "mvn -Djdk=6 ..." where ... is the Maven commands to execute.

Note that more than one profile can be active at once. Since profiles can contain the same types of configuration there can be clashes. If two profiles clash the last to be activated will override those activated earlier.