Finally trying out Maven 2

While many people are saying that Maven 2 is really a terrible terrible tool and stupid for great, great many reasons, recently I have finally been trying out Maven when I had to reorganize a generic algorithm into a separate library and I wanted to end up with a nice build process and managed dependencies.

On Mac OS X, Maven 2 can be installed easily via MacPorts. I started with the getting started guide and created my library project called mylib from the command line

$ mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.mylib -DartifactId=mylib

This has created a directory named mylib for the new project, and this directory contains a file named pom.xml. After moving my sources to ${basedir}/src/main/java, I had to resolve some external dependencies. My library is only dependent on Commons IO, Commons Lang and Commons Logging, so I added the following to the pom.xml under dependencies.

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
<scope>compile</scope>
</dependency>

For Java 5 source compatibility you will have to add the following lines to your pom.xml:

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<inherited>true</inherited>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>

Note that when compiling the application sources for the first time with

$ mvn compile

Maven will need to download all the plugins and related dependencies.

After successfully compiling the library’s sources, I’ve put my JUnit tests in the directory ${basedir}/src/test/java. They can be executed with

$ mvn test

In order to use Log4J logging during tests, put the log4j.xml file in the ${basedir}/src/test/config directory. Then add the following lines to the build/testResources element in your pom.xml:

<testResources>
<testResource>
<directory>src/test/config</directory>
<includes>
<include>log4j.xml</include>
</includes>
</testResource>
</testResources>

A final tip: if you are using Eclipse, Maven can create Eclipse projects for you with

$ mvn eclipse:eclipse

which can then be imported into Eclipse as existing projects.

So far I’m quite pleased with Maven: I managed to create a new project for my library in no time (< 5 minutes), with a nice build process and dependency management. IMO much better than manually copying build.xml files from other projects and third-party jars around. 🙂

Leave a Reply