Wednesday, October 8, 2008

Maven 2 - Easy Dependency Management for Production

In this post I will cover basic examples of the following maven 2 plugins:
  • maven-dependency-plugin
  • maven-jar-plugin
  • maven-assembly-plugin.
I have been using Maven 1.x for a long time. Now, I am more working with MVN (aka Maven 2) and I found that with MVN it is very easy to prepare distribution package including all dependencies. More specifically, I found two nice approaches how to handle CLASSPATH dependencies during mvn package phase.

The first approach:
maven-dependency-plugin and maven-jar-plugin

As a result of utilization of these two plugins you can have your application classes packed into a jar file and a lib folder next to it which contains all the needed jar libraries. Moreover, the application jar will contain references to all the jar libraries in the manifest. This means that you don't have to put libraries on the CLASSPATH explicitely as long as they are kept in the lib folder.
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/release-${project.version}/lib
</outputDirectory>
<includeScope>runtime</includeScope>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.yourcompany.ClasswithStaticMainMethod</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>

The second approach:
maven-assembly-plugin

This plugin allows you to include any kind of resource into the application jar. In case of third-party libraries it means that it un-zips all dependent jar archives and copy compiled classes next to your application classes. Then it zips everything into a single jar file.
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.yourcompany.ClasswithStaticMainMethod</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>


Related resources:
Original mail thread from maven mail archive: here

No comments: