Tuesday, September 20, 2011

Recipe#6: Configure Maven2

When I started programming 8 years ago, ANT was the build tool of choice for Java programs. These days, you are better off using Apache Maven, which adds dependency management, build profiles, and automation for common tasks (like documentation and site generation, distribution, and test).

To install Maven:
  1. Download the package from http://maven.apache.org/download.html.
  2. Unzip the contents to a location that will be Maven's home directory.
  3. Set the "M2_HOME" environment variable to point to the home directory. Some plugins still require it, although it is no longer necessary for Maven itself.
  4. Add %M2_HOME%\bin to environment PATH so that you may run the mvn command from anywhere.
By default, Maven creates a local repository under %user_profile%\.m2. To control where artifacts and dependencies are stored, specify an %M2_REPO% environment variable that points to a directory where you want the local repository.

Because I develop in the Eclipse IDE, it is configured it with the m2eclipse Maven plugin, which allows me to void a DOS console when I build projects and do everything in Eclipse:
  1. In Eclipse, create an update site for m2eclipse [Help > Install New Software. Add m2eclipse=http://download.eclipse.org/technology/m2e/releases.
  2. Select "Maven Integration for Eclipse", click [Next]. Agree to license terms and [Install]. You will need to restart Eclipse.
Before you start using m2eclipse, it pays to look over the configuration. Among the things I changed: having the plugin use the Maven installation from earlier because the plugin references non-release or snapshot version of Maven. If you have other programs or scripts that use Maven outside Eclipse, this action promotes build consistency. Also consider the settings file, which you can now edit in Eclipse.

Some recommended reads on Maven2 can be found at http://maven.apache.org/articles.html. I like "Maven 2: Effective Implementation" because it also touches on Apache Archiva and Continuum. Otherwise "Apache Maven 3 Cookbook" will get you up-to-date on the latest usage of Maven.