Thursday, January 14, 2010

Maven - It Isn't ALL Bad!

Nope, this isn't a blog post to start another war between Ant and Maven. I am and will remain a huge fan of Ant for many years to come. Having used it extensively in the last decade, I know the in's and out's of writing huge huge build files. Yes, huge build files.

However, I was trying a few new projects and all the samples I tried were mostly in Maven. It had been my New Years Resolution for many years to learn Maven. But, they remained just that , New Years Resolutions and never got a chance to actually either learn or use it in any of my projects.

Last week, I had a few hours of free time, and decided to actually try Maven from scratch. I was always intimidated by the POM; which is THE PROJECT OBJECT MODEL. No idea why. I tried a few simple commands and was able to clearly understand and learn Maven the right way.

If given an option now, what will I choose for my new project, can you guess? Nope, you thought I would choose Maven, you are wrong. I would still use Ant. However, if I am writing an article, or giving a presentation, I would rather use Maven. It is so simple to create a new project, where Maven does all the work for you.

  • Open a command prompt, and type the following command:
    • mvn archetype:create -DgroupId=org.meeras.sample -DartifactId=sample -DpackageName=org.meeras.sample
 The output in the command window will be as such:

 At this point, Maven created the entire directory structure for me as shown below. How cool is that?

  • The POM at this point is very simple, with just JUnit as it's dependency. If you want to see effective POM, which Maven always executes from, run the following command to see all the Parent POM's and also the Super POM.
    • mvn help:effective-pom
The output now within the command window should be something like this:

If you are having trouble finding from where Maven is getting all the information, just try the above command. You will see the merged POM, which can help in many ways.

  •  Maven creates a simple Java class with a static main which you can run from the command line where the POM.xml file resides .This following command compiles, tests, packages and installs the sample application.
    • mvn install .
Now that you have the jar file, you can run it.
C:\dev\projects\maven-samples\sample>java -cp target/sample-1.0-SNAPSHOT.jar org
Hello World!

In one step I was able to create an entire project structure. That's the biggest plus for Maven. Convention over Configuration.

So, that's it for today. I will write more about Maven the next time I do something even more interesting.