📄 Page
1
Maven: The Definitive Guide, 1st Edition by Sonatype Company Publisher: O'Reilly Media, Inc. Pub Date: October 1, 2008 Print ISBN-13: 978-0-596-51733-5 Pages: 250 Overview For too long, developers have worked on disorganized application projects, where every part seemed to have its own build system, and no common repository existed for information about the state of the project. Now there's help. The long-awaited official documentation to Maven is here. Written by Maven creator Jason Van Zyl and his team at Sonatype, Maven: The Definitive Guide clearly explains how this tool can bring order to your software development projects. Maven is largely replacing Ant as the build tool of choice for large open source Java projects because, unlike Ant, Maven is also a project management tool that can run reports, generate a project website, and facilitate communication among members of a working team. To use Maven, everything you need to know is in this guide. The first part demonstrates the tool's capabilities through the development, from ideation to deployment, of several sample applications -- a simple software development project, a simple web application, a multi-module project, and a multi- module enterprise project. The second part offers a complete reference guide that includes: • The POM and Project Relationships • The Build Lifecycle • Plugins • Project website generation • Advanced site generation • Reporting • Properties • Build Profiles • The Maven Repository • Team Collaboration • Writing Plugins • IDEs such as Eclipse, IntelliJ, ands NetBeans • Using and creating assemblies • Developing with Maven Archetypes Several sources for Maven have appeared online for some time, but nothing served as an introduction and comprehensive reference guide to this tool -- until now. Maven: The Definitive Guide is the ideal book to help you manage development projects for software, web applications, and enterprise applications. And it comes straight from the source. Editorial Reviews Product Description For too long, developers have worked on disorganized application projects, where every part seemed to have its own build system, and no common repository existed for information about the state of the project. Now there's help. The long-awaited official documentation to Maven is here. Written by Maven creator Jason Van Zyl and his team at Sonatype, Maven: The Definitive Guide clearly explains how this tool can bring order to your software development projects. Maven is largely replacing Ant as the build tool of choice for large open source Java projects because, unlike Ant, Maven is also a project management tool that can run reports, generate a project website, and facilitate communication among members of a working team. To use Maven, everything you need to know is in this guide. The first part demonstrates the tool's capabilities through the development, from ideation to deployment, of several sample applications -- a simple software development project, a simple web application, a multi-module project, and a multi-module enterprise project. The second part offers a complete reference guide that includes: The POM and Project Relationships The Build Lifecycle Plugins Project website generation Advanced site generation Reporting Properties Build Profiles The Maven Repository Team Collaboration Writing Plugins IDEs such as Eclipse, IntelliJ, ands NetBeans Using and creating assemblies Developing with Maven Archetypes Several sources for Maven have appeared online for some time, but nothing served as an introduction and comprehensive reference guide to this tool -- until now. Maven: The Definitive Guide is the ideal book to help you manage development projects for software, webapplications, and enterprise applications. And it comes straight from the source.
📄 Page
2
Preface Although there are a number of references for Maven online, there is no single, well-written narrative for introducing Maven that can serve as both an authoritative reference and an introduction. What we've tried to do with this effort is provide such a narrative coupled with useful reference material. P.1. Maven... What Is It? The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a "build tool": a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team. Here is a more formal definition of Apache Maven: Maven is a project management tool that encompasses a Project Object Model, a set of standards, a project lifecycle, a dependency management system, and logic for executing plugin goals at defined phases in a lifecycle. When you use Maven, you describe your project using a well-defined Project Object Model, Maven can then apply cross-cutting logic from a set of shared (or custom) plugins. Don't let the fact that Maven is a "project management" tool scare you away. If you are just looking for a build tool, Maven will do the job. In fact, the first few chapters of Part 2 will deal with the most common use case: using Maven to build and distribute your project. P.2. Font Conventions This book follows certain conventions for font usage. Understanding these conventions upfront makes it easier to use this book: Italic Used for filenames, file extensions, URLs, application names, emphasis, and new terms when they are first introduced. Constant width Used for Java™ class names, methods, variables, properties, data types, database elements, and snippets of code that appear in text. Constant width bold Used for commands you enter at the command line and to highlight new code inserted in a running example. Constant width italic Used to annotate output. P.3. Maven Writing Conventions The book follows certain conventions for naming and font usage in relation to Apache Maven. Understanding these conventions upfront makes it easier to read this book:
📄 Page
3
Compiler plugin Maven plugins are capitalized. create goal Maven goal names are displayed in a constant width font. plugin Maven revolves around the heavy use of plugins, but you won't find plugin defined in the dictionary. This book uses "plugin" without a hyphen because it is easier to read and write and because it is a standard throughout the Maven community. Maven Lifecycle, Maven Standard Directory Layout, Project Object Model Core Maven concepts are capitalized whenever they are referenced in the text. goalParameter A Maven goal parameter is displayed in a constant width font. compile phase Lifecycle phases are displayed in a constant width font. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. P.4. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product's documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Maven: The Definitive Guide by Sonatype. Copyright 2008 Sonatype, 978-0-596-51733-5."
📄 Page
4
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. P.5. Safari® Books Online NOTE When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O'Reilly Network Safari Bookshelf. Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free athttp://safari.oreilly.com. P.6. How to Contact Us Please address comments and questions concerning this book to the publisher: O'Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international/local) 707-829-0104 (fax) O'Reilly's web page for this book, where we list errata, examples, or any additional information. You can access this page at: http://www.oreilly.com/catalog/9780596517335 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at: http://www.oreilly.com P.7. Acknowledgments Sonatype would like to thank the following contributors who have provided feedback that improved the quality of this book. Thanks to Chad Gorshing, Marcus Biel, Brian Dols, Mangalaganesh Balasubramanian, Marius Kruger, and Mark Stewart. Special thanks to Joel Costigliola for helping debug and correct the Spring web chapter. Stan Guillory was practically a contributing author given the number of corrections he posted to the book's Get Satisfaction page. Thank you, Stan. Special thanks to Richard Coasby of Bamboo for acting as the provisional grammar consultant. Sarah Schneider and Marlowe Shaeffer of O'Reilly Media, and Mark Jewett of Appingo, should receive medals for the extreme patience they displayed as this book continued to miss schedule after schedule. Thank you, Sarah, and the entire production department for making this book a success. Thanks to Mike Loukides and Mike Hendrickson for providing the necessary editorial oversight to make sure that we were given enough time and feedback to publish a book that will remain relevant in the months and years to come. Thanks to all of the authors, especially Bruce Snyder, Brian Fox, John Casey, Jason van Zyl, and Eugene Kuleshov. Everyone at Sonatype played a part in the content of this book, and everyone worked together to help us create a foundation for this documentation. Thanks to all of our contributing authors, especially Eric Redmond. Tim O'Brien would like to thank his perfect wife, Susan, and child, Josephine.
📄 Page
5
Part 1: Introduction The two chapters in this brief introduction describe Maven, explain how it stacks up to and improves on other build tools throughout time, and show you how to install and run it on all platforms. If you've already installed Maven and are familiar with the core concepts of the tool, you might want to skip ahead to Part 2. Then again, even if you are already somewhat familiar with Maven, you might want to peruse some of the propaganda in this introduction so you're prepared when people start asking you why your organization or project should use Maven. After this section, you should have a better idea of what Maven is, what makes it different from some of the other options out there, and how to install it and learn more from the built-in help facilities.
📄 Page
6
Chapter 1. Introducing Apache Maven Convention over Configuration A Common Interface Universal Reuse Through Maven Plugins Conceptual Model of a "Project" Is Maven an Alternative to XYZ? Comparing Maven and Ant Summary 1.1. Convention over Configuration Convention over configuration is a simple concept. Systems, libraries, and frameworks should assume reasonable defaults without requiring that unnecessary configuration systems should "just work." Popular frameworks such as Ruby on Rails and EJB3 have started to adhere to these principles in reaction to the configuration complexity of frameworks such as the initial Enterprise JavaBeans™ (EJB) specifications. An illustration of convention over configuration is something like EJB3 persistence. All you need to do to make a particular bean persistent is to annotate that class with @Entity. The framework will then assume table names and column names from the name of the class and the names of the properties. Hooks are provided for you to override these names if the need arises, but, in most cases, you will find that using the framework-supplied defaults results in a faster project execution. Maven incorporates the concept by providing sensible default behaviors for projects. Without customization, source code is assumed to be in${basedir}/src/main/java and resources are assumed to be in ${basedir}/src/main/resources. Tests are assumed to be in${basedir}/src/test, and a project is assumed to produce a JAR (Java ARchive) file. Maven assumes that you want to compile byte code to${basedir}/target/classes and then create a distributable JAR file in ${basedir}/target. Although this might seem trivial, consider the fact that most Ant-based builds have to define the locations of these directories in every subproject. Maven's adoption of convention over configuration goes further than just simple directory locations; Maven's core plugins apply a common set of conventions for compiling source code, packaging distributions, generating web sites, and many other processes. Maven's strength comes from the fact that it is "opinionated." It has a defined lifecycle and a set of common plugins that know how to build libraries and web applications. If you follow the convention, Maven will require almost zero effort—just put your source in the correct directory, and Maven will take care of the rest. One side effect of using systems that follow "convention over configuration" is that end users might feel that they are forced to use a particular setup. While it is certainly true that Maven has some central opinions that shouldn't be challenged, most of the defaults can be customized. For example, the location of a project's source code and resources can be customized, names of JAR files can be customized, and through the development of custom plugins, almost any behavior can be tailored to your specific environment's requirements. If you don't follow convention, Maven will allow you to customize defaults in order to adapt to your requirements. 1.2. A Common Interface Before Maven provided a common interface for building software, every single project had someone dedicated to managing a completely custom build system, and developers had to take time away from developing software to learn about the idiosyncrasies of each new project they wanted to contribute to. In 2001, you'd take a completely different approach to building a project such as Apache Turbine than you would to building a project such as Tomcat. If a new source analysis tool came out that would perform static analysis on source code, or if someone developed a new unit testing framework, everyone would have to drop what they were doing and figure out how to fit it into each project's custom build environment. How would you run unit tests? There were a thousand different answers. This environment was characterized by endless arguments about tools and build procedures. The age before Maven was an age of inefficiency—the age of the "Build Engineer." Today, most open source developers have used or are currently using Maven to manage new software projects. This transition is less about developers moving from one build tool to another and more about developers starting to adopt a common interface for project builds. As software systems have become more modular, build systems have become more complex, and the number of projects has skyrocketed. Before Maven, when you wanted to check out a project such as Apache ActiveMQ or Apache ServiceMix from Subversion and build it from source, you really had to set aside about an hour to figure out the build system for each particular project. What does the project need to build? What libraries do I need to download? Where do I put them? What goals can I execute in the build? In the best case, it took a few minutes
📄 Page
7
to figure out a new project's build, and in the worst cases (like the old Servlet API implementation in the Jakarta Project), a project's build was so difficult it would take many hours just to get to the point where a new contributor could edit source and compile the project. These days, with Maven, you check it out from source, and you run mvn install. Although Maven provides an array of benefits, including dependency management and reuse of common build logic through plugins, the core reason it has succeeded is that it has defined a common interface for building software. When you see that a project such as Apache Wicket uses Maven, you can assume that you'll be able to check it out from source and build it with mvn install without much hassle. You know where the ignition key goes, and you know that the gas pedal is on the right and the brake is on the left. 1.3. Universal Reuse Through Maven Plugins The core of Maven is pretty dumb; it doesn't know how to do much beyond parsing a few XML documents and keeping track of a lifecycle and a few plugins. Maven has been designed to delegate most responsibility to a set of Maven plugins that can affect the Maven lifecycle and offer access to goals. Most of the action in Maven happens in plugin goals that take care of things like compiling source, packaging bytecode, publishing sites, and any other task that needs to happen in a build. The Maven you download from Apache doesn't know much about packaging a WAR file or running JUnit tests; most of Maven's intelligence is implemented in the plugins, and the plugins are retrieved from the Maven repository. In fact, the first time you run something like mvn install with a brand new Maven installation, it retrieves most of the core Maven plugins from the central Maven repository. This is more than just a trick to minimize the download size of the Maven distribution; this is behavior that allows you to upgrade a plugin to add capability to your project's build. The fact that Maven retrieves both dependencies and plugins from the remote repository allows for universal reuse of build logic. The Maven Surefire plugin is responsible for running unit tests. At some point between version 1.0 and the version that is in wide use today, someone decided to add support for the TestNG unit testing framework in addition to the support for JUnit. This happened in a way that didn't break backward compatibility—if you were using the Surefire plugin to compile and execute JUnit 3 unit tests, and you upgraded to the most recent version of the Surefire plugin, your tests continued to execute without fail. You also gained new functionality, so if you wanted to execute unit tests in TestNG, you now had that ability, thanks to the efforts of the maintainers of the Surefire plugin. You also gained the ability to run annotated JUnit 4 unit tests. You gained all of these capabilities without having to upgrade your Maven installation or install new software. Most importantly, nothing about your project had to change aside from a version number for a plugin in a POM. It is this mechanism that affects much more than the Surefire plugin: projects are compiled with a Compiler plugin, projects are turned into JAR files with a Jar plugin, and there are plugins for running reports, plugins for executing JRuby and Groovy code, as well as plugins to publish sites to remote servers. Maven has abstracted common build tasks into plugins that are maintained centrally and shared universally. If the state of the art changes in any area of the build, if some new unit testing framework is released or if some new tool is made available, you don't have to be the one to hack your project's custom build system to support it. You benefit from the fact that plugins are downloaded from a remote repository and maintained centrally. This is what is meant by universal reuse through Maven plugins. 1.4. Conceptual Model of a "Project" Maven maintains a model of a project: you are not just compiling source code into bytecode, you are developing a description of a software project and assigning a unique set of coordinates to a project. You are describing the attributes of the project. What is the project's license? Who develops and contributes to the project? What other projects does this project depend on? Maven is more than just a "build tool"; it is more than just an improvement on tools such as make and Ant; it is a platform that encompasses a new semantics related to software projects and software development. This definition of a model for every project enables such features as: Dependency management A project is defined as unique coordinates that consists of a group identifier, artifact identifier, and version. Projects can now use these coordinates to declare dependencies. Remote repositories Related to dependency management, we can use the coordinates defined in the Maven Project Object Model (POM) to create repositories of Maven artifacts.
📄 Page
8
Universal reuse of build logic Plugins are coded to work with the POM; they are not designed to operate on specific files in known locations. Everything is abstracted into the model—plugin configuration and customization happens in the model. Tool portability and integration Tools such as Eclipse, NetBeans, and IntelliJ now have a common place to find information about a project. Before the advent of Maven, every integrated development environment (IDE) had a different way to store what was essentially a custom POM. Maven has standardized this description, and although each IDE continues to maintain custom project files, they can be easily generated from the model. Easy searching and filtering of project artifacts Tools such as Nexus allow you to index and search the contents of a repository using the information stored in the POM. Maven has provided a foundation for the beginnings of a consistent semantic description of a software project. 1.5. Is Maven an Alternative to XYZ? So, sure, Maven is an alternative to Ant, but Apache Ant continues to be a great, widely used tool. It has been the reigning champion of Java builds for years, and you can integrate Ant build scripts with your project's Maven build very easily. This is a common usage pattern for a Maven project. On the other hand, as more and more open source projects move to Maven as a project management platform, working developers are starting to realize that Maven not only simplifies the task of build management, it is helping to encourage a common interface between developers and software projects. Maven is more of a platform than a tool. Although you can consider Maven an alternative to Ant, you are comparing apples to oranges. "Maven" includes more than just a build tool. This is the central point that makes all of the Maven versus Ant, Maven versus Buildr, Maven versus Gradle arguments irrelevant. Maven isn't totally defined by the mechanics of your build system. It isn't about scripting the various tasks in your build as much as it is about encouraging a set of standards, a common interface, a lifecycle, a standard repository format, a standard directory layout, etc. It certainly isn't about what format the POM happens to be in, i.e., XML versus YAML versus Ruby. Maven is much larger than that, and Maven refers to much more than the tool itself. When this book talks about Maven, it is referring to the constellation of software, systems, and standards that support it. Buildr, Ivy, Gradle—all of these tools interact with the repository format that Maven helped create, and you could just as easily use a tool such as Nexus to support a build written entirely in Buildr. Nexus is introduced in Chapter 16. Although Maven is an alternative to many of these tools, the community needs to evolve beyond seeing technology as a zero-sum game between unfriendly competitors in a contest for users and developers. This might be how large corporations relate to one another, but it has very little relevance to the way that open source communities work. The headline "Who's winning? Ant or Maven?" isn't very constructive. If you force us to answer this question, we're definitely going to say that Maven is a superior alternative to Ant as a foundational technology for a build; at the same time, Maven's boundaries are constantly shifting and the Maven community is constantly trying to seek out new ways to become more ecumenical, interoperable, and cooperative. The core tenets of Maven are declarative builds, dependency management, repository managers, and universal reuse through plugins, but the specific incarnation of these ideas at any given moment is less important than the sense that the open source community is collaborating to reduce the inefficiency of "enterprise-scale builds." 1.6. Comparing Maven and Ant Although the previous section should convince you that the authors of this book have no interest in creating a feud between Apache Ant and Apache Maven, we are cognizant of the fact that most organizations have to make a decision between Ant and Maven. In this section, we compare and contrast the tools. Ant excels at build process; it is a build system modeled after make with targets and dependencies. Each target consists of a set of instructions that are coded in XML. There is a <copy> task and a <javac> task as well as a <jar> task. When you use Ant, you supply it with specific instructions for compiling and packaging your output. Look at the simple build.xml file shown in Example 1-1.
📄 Page
9
Example 1-1. A simple Ant build.xml file <project name="my-project" default="dist" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src/main/java"/> <property name="build" location="target/classes"/> <property name="dist" location="target"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> </target> <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="dist" depends="compile" description="generate the distribution" > <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/> </target> <target name="clean" description="clean up" > <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${dist}"/> </target> </project> In this simple Ant example, you can see how you have to tell Ant exactly what to do. There is a compile goal that includes the javac task, which compiles the source in the src/main/java directory to the target/classes directory. You have to tell Ant exactly where your source is, where you want the resulting bytecode to be stored, and how to package this all into a JAR file. Although some recent developments help make Ant less procedural, a developer's experience with Ant is in coding a procedural language written in XML. Contrast the previous Ant example with a Maven example. In Maven, to create a JAR file from some Java source, all you need to do is create a simple pom.xml, place your source code in ${basedir}/src/main/java, and then run mvn install from the command line. The example Maven pom.xml that achieves the same results as the simple Ant file listed in Example 1-1 is shown in Example 1-2. Example 1-2. A simple Maven pom.xml <project> <modelVersion>4.0.0</modelVersion> <groupId>org.sonatype.mavenbook</groupId> <artifactId>my-project</artifactId> <version>1.0</version> </project> That's all you need in your pom.xml. Running mvn install from the command line will process resources, compile source, execute unit tests, create a JAR, and install the JAR in a local repository for reuse in other projects. Without modification, you can run mvn site and then find an index.html file in target/site that contains links to Javadoc and a few reports about your source code. Admittedly, this is the simplest possible example project: a project that contains only source code and produces a JAR; a project that follows Maven conventions and doesn't require any dependencies or customization. If we want to start customizing the behavior, our pom.xml is going to grow in size, and in the largest of projects, you can see collections of very complex Maven POMs that contain a great deal of plugin customization and dependency declarations. But even when your project's POM files become more substantial, they hold an entirely different kind of information from the build file of a similarly sized project using Ant. Maven POMs contain declarations: "This is a JAR project," and "The source code is in src/main/java." Ant build files contain explicit instructions: "This is project," "The source is insrc/main/java," "Run javac against this directory," "Put the results in target/classses," "Create a JAR from the ....", etc. Where Ant has to be explicit about the process, there is something "built-in" to Maven that just knows where the source code is and how it should be processed.
📄 Page
10
The differences between Ant and Maven in this example are: Apache Ant • Ant doesn't have formal conventions such as a common project directory structure; you have to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven't been codified into the product. • Ant is procedural; you have to tell Ant exactly what to do and when to do it. You have to tell it to compile, then copy, then compress. • Ant doesn't have a lifecycle; you have to define goals and goal dependencies. You have to attach a sequence of tasks to each goal manually. Apache Maven • Maven has conventions: in the example, it already knew where your source code was because you followed the convention. It put the bytecode in target/classes, and it produced a JAR file in target. • Maven is declarative; all you had to do was create a pom.xml file and put your source in the default directory. Maven took care of the rest. • Maven has a lifecycle, which you invoked when you executed mvn install. This command told Maven to execute a series of sequence steps until it reached the lifecycle. As a side effect of this journey through the lifecycle, Maven executed a number of default plugin goals that did things such as compile and create a JAR. Maven has built-in intelligence about common project tasks in the form of Maven plugins. If you want to write and execute unit tests, all you need to do is write the tests, place them in ${basedir}/src/test/java, add a test-scoped dependency on either TestNG or JUnit, and runmvn test. If you want to deploy a web application and not a JAR, all you need to do is change you project type to WAR and put your docroot in ${basedir}/src/main/webapp. Sure, you could do all of this with Ant, but you would be writing the instructions from scratch. In Ant, you would first have to figure out where the JUnit JAR file should be, and then you would have to create a classpath that includes the JUnit JAR file, and then you would tell Ant where it should look for test source code, write a goal that compiles the test source to bytecode, and execute the unit tests with JUnit. Without supporting technologies such as antlibs and Ivy (and even with these supporting technologies), Ant has the feeling of a custom procedural build. An efficient set of Maven POMs in a project that adheres to Maven's assumed conventions has surprisingly little XML compared to the Ant alternative. Another benefit of Maven is the reliance on widely shared Maven plugins. Everyone uses the Maven Surefire plugin for unit testing, and if someone adds support for a new unit testing framework, you can gain new capabilities in your own build just by incrementing the version of a particular Maven plugin in your project's POM. The decision to use Maven or Ant isn't a binary one, and Ant still has a place in a complex build. If your current build contains some highly customized process, or if you've written some Ant scripts to complete a specific process in a specific way that cannot be adapted to the Maven standards, you can still use these scripts with Maven. Ant is made available as a core Maven plugin. Custom Maven plugins can be implemented in Ant, and Maven projects can be configured to execute Ant scripts within the Maven project lifecycle. 1.7. Summary This introduction has been kept purposefully short. We have covered a basic outline of what Maven is and how it stacks up to and improves on other build tools throughout time. The next chapter will explain how to install and run Maven, and Chapter 3 will dive into a simple project and show how Maven can perform phenomenal tasks with the smallest amount of configuration.
📄 Page
11
Chapter 2. Installing and Running Maven This chapter contains very detailed instructions for installing Maven on a number of different platforms. Instead of assuming a level of familiarity with installing software and setting environment variables, we've opted to be as thorough as possible to minimize any problems that might arise due to a partial installation. The only thing this chapter assumes is that you've already installed a suitable Java Development Kit (JDK). If you are just interested in installation, you can move on to the rest of the book after reading through the "Section 2.2" and "Section 2.3" sections. If you are interested in the details of your Maven installation, this entire chapter will give you an overview of what you've installed and the Apache Software License. 2.1. Verify Your Java Installation Although Maven can run on Java 1.4, this book assumes that you are running at least Java 5. Go with the most recent stable JDK available for your operating system. Either Java 5 or Java 6 will work with all of the examples in this book: % java -version java version "1.6.0_02" Java(TM) SE Runtime Environment (build 1.6.0_02-b06) Java HotSpot(TM) Client VM (build 1.6.0_02-b06, mixed mode, sharing) Maven works with all certified Java-compatible development kits, and a few noncertified implementations of Java. The examples in this book were written and tested against the official Java Development Kit releases downloaded from the Sun Microsystems web site. If you're working with a Linux distribution, you may need to download Sun's JDK yourself and make sure it's the version you're invoking (by runningjava -version, as shown earlier). Now that Sun has open sourced Java, this will hopefully improve in the future, and we'll get the Sun Java Runtime Environment (JRE) and JDK by default even in purist distributions. Until that day, you may need to do some of your own downloading. 2.2. Downloading Maven You can download Maven from the Apache Maven project web site by going to http://maven.apache.org/download.html. When downloading Maven, make sure you choose the latest version of Apache Maven from the web site. The latest version of Maven at the time of this writing is Maven 2.0.9. If you are not familiar with the Apache Software License, you should get acquainted with the terms of the license before you start using the product. More information on the Apache Software License can be found in Section 2.8," later in this chapter. 2.3. Installing Maven There are wide differences between operating systems such as Mac OS X and Microsoft Windows, and there are subtle differences between different versions of Windows. Luckily, the process of installing Maven on all of these operating systems is relatively painless and straightforward. The following sections outline the recommended best-practice for installing Maven on a variety of operating systems. 2.3.1. Installing Maven on Mac OS X You can download a binary release of Maven from http://maven.apache.org/download.html. Download the current release of Maven in a format that is convenient for you to work with. Pick an appropriate place for it to live, and expand the archive there. If you expanded the archive into the directory /usr/local/maven-2.0.9, you may want to create a symbolic link to make it easier to work with and to avoid the need to change any environment configuration when you upgrade to a newer version: /usr/local % ln -s maven-2.0.9 maven /usr/local % export M2_HOME=/usr/local/maven /usr/local % export PATH=${M2_HOME}/bin:${PATH} Once Maven is installed, you need to do a couple of things to make it work correctly. You need to add its bin directory in the distribution (in this example, /usr/local/maven/bin) to your command path. You also need to set the environment variable M2_HOME to the top-level directory you installed (in this example, /usr/local/maven). NOTE
📄 Page
12
Installation instructions are the same for both OS X Tiger and Leopard. It has been reported that Maven 2.0.6 is shipping with a preview release of Xcode. If you have installed XCode, run mvn from the command line to check availability. XCode installs Maven in/usr/share/maven. We recommend installing the most recent version of Maven 2.0.9, as there have been a number of bug fixes and improvements since Maven 2.0.9 was released. You'll need to add both M2_HOME and PATH to a script that will run every time you log in. To do this, add the following lines to .bash_login: export M2_HOME=/usr/local/maven export PATH=${M2_HOME}/bin:${PATH} Once you've added these lines to your own environment, you will be able to run Maven from the command line. NOTE These installation instructions assume that you are running bash. 2.3.2. Installing Maven on Microsoft Windows Installing Maven on Windows is very similar to installing Maven on Mac OS X, the main differences being the installation location and the setting of an environment variable. This book assumes a Maven installation directory located at c:\Program Files\maven-2.0.9, but it won't make a difference if you install Maven in another directory as long as you configure the proper environment variables. Once you've unpacked Maven in the installation directory, you will need to set two environment variables—PATH and M2_HOME. To set theseenvironment variables from the command line, type in the following commands: C:\Users\tobrien > set M2_HOME=c:\Program Files\maven-2.0.9 C:\Users\tobrien > set PATH=%PATH%;%M2_HOME%\bin Setting these environment variables on the command line will allow you to run Maven in your current session, but unless you add them to the system environment variables through the control panel, you'll have to execute these two lines every time you log into your system. Set both M2_HOME and PATH to point to your Maven installation. 2.3.3. Installing Maven on Linux To install Maven on a Linux machine, follow the exact procedure outlined in Section 2.3.1," earlier in this chapter. 2.3.4. Installing Maven on FreeBSD or OpenBSD To install Maven on a FreeBSD or OpenBSD machine, follow the exact procedure outlined in Section 2.3.1," earlier in this chapter. 2.4. Testing a Maven Installation Once Maven is installed, you can see if it is installed properly by running mvn -v from the command line. If Maven has been installed, you should see something resembling the following output: ~/examples $ mvn -v Maven 2.0.9 If you see this output, you know that Maven has been successfully installed. If you do not see this output and your operating system cannot find the mvn command, make sure that your PATH and M2_HOME environment variables have been properly set. 2.5. Maven Installation Details Maven's download measures in at roughly 1.5 MiB.[1] It has attained such a slim download size because the core of Maven has been designed to retrieve plugins and dependencies from a remote repository on demand. When you start using
📄 Page
13
Maven, it will start to download plugins to a local repository as described in Section 2.5.1," later in this chapter. In case you are curious, let's take a quick look at what is inMaven's installation directory: [1] Ever purchased a 200 GB hard drive only to realize that it showed up as less than 200 GiB when you installed it? Computers understand Gibibytes, but retailers sell products using Gigabytes. MiB stands for Mebibyte, which is defined as 220 or 10242. These binary prefix standards are endorsed by the Institute of Electrical and Electronics Engineers (IEEE), the International Committee for Weights and Measures (CIPM), and the International Electrotechnical Commission (IEC). For more information about Kibibytes, Mebibytes, Gibibytes, and Tebibytes, see http://en.wikipedia.org/wiki/Mebibyte. /usr/local/maven $ ls -p1 LICENSE.txt NOTICE.txt README.txt bin/ boot/ conf/ lib/ LICENSE.txt contains the software license for Apache Maven. This license is described in some detail later in Section 2.8." NOTICE.txtcontains some notices and attributions required by libraries that Maven depends on. README.txt contains some installation instructions.bin/ contains the mvn script that executes Maven. boot/ contains a JAR file (classwords-1.1.jar) that is responsible for creating the Class Loader in which Maven executes. conf/ contains a global settings.xml that can be used to customize the behavior of your Maven installation. If you need to customize Maven, it is customary to override any settings in a settings.xml file stored in ~/.m2. lib/ contains a single JAR file (maven-core-2.0.9-uber.jar) that contains the core of Maven. 2.5.1. User-Specific Configuration and Repository Once you start using Maven extensively, you'll notice that Maven has created some local user-specific configuration files and a local repository in your home directory. In ~/.m2, there will be: settings.xml A file containing user-specific configuration for authentication, repositories, and other information to customize the behavior of Maven. repository/ This directory contains your local Maven repository. When you download a dependency from a remote Maven repository, Maven stores a copy of the dependency in your local repository. NOTE In Unix (and OS X), your home directory will be referred to using a tilde (i.e., ~/bin refers to /home/tobrien/bin). In Windows, we will also be using ~ to refer to your home directory. In Windows XP, your home directory is C:\Documents and Settings\tobrien, and in Windows Vista, your home directory is C:\Users\tobrien. From this point forward, you should translate paths such as ~/m2 to your operating system's equivalent. 2.5.2. Upgrading a Maven Installation If you've installed Maven on a Mac OS X or Unix machine according to the details given in Section 2.3.1" and Section 2.3.3," it should be easy to upgrade to newer versions of Maven when they become available. Simply install the newer version of Maven (/usr/local/maven-2.future) next to the existing version of Maven (/usr/local/maven-2.0.9). Then, switch the symbolic link /usr/local/maven from/usr/local/maven-2.0.9 to /usr/local/maven-2.future. Since you've already set your M2_HOME variable to point to /usr/local/maven, you won't need to change any environment variables. If you've installed Maven on a Windows machine, simply unpack Maven to c:\Program Files\maven-2.future and update your M2_HOMEvariable. 2.6. Getting Help with Maven
📄 Page
14
Although this book aims to be a comprehensive reference, there are going to be topics we miss and special situations and tips that are not covered. The core of Maven is very simple, but the real work in Maven happens in the plugins, and there are too many plugins available to cover them all in one book. When you encounter problems and features that are not covered in this book, we suggest searching for answers at the following locations: http://maven.apache.org This is the first place you should look; the Maven web site contains a wealth of information and documentation. Every plugin has a few pages of documentation, and it provides a series of "quick start" documents that will be helpful in addition to the contents of this book. Although the Maven site contains plenty of information, it can also be a frustrating, confusing, and overwhelming. A custom Google search box on the main Maven page will search known Maven sites for information. This provides better results than a generic Google search. Maven user mailing list The Maven user mailing list is the place for users to ask questions. Before you ask a question on the user mailing list, you will want to search for any previous discussion that might relate to your question. It is bad form to ask a question that has already been asked without first checking to see whether an answer already exists in the archives. There are a number of useful mailing list archive browsers; we've found Nabble to be the most useful. You can browse the user mailing list archives here:http://www.nabble.com/Maven---Users-f178.html. You can join the user mailing list by following the instructions available here:http://maven.apache.org/mail-lists.html. http://www.sonatype.com Sonatype maintains an online copy of this book and other tutorials related to Apache Maven. NOTE Despite the best efforts of some very dedicated Maven contributors, the Maven web site is poorly organized and full of incomplete (and sometimes misleading) snippets of documentation. Throughout the Maven community there is a lack of a common standards for plugin documentation. Some plugins are heavily documented, whereas others lack even the most basic instructions for usage. Often your best bet is to search for a solution in the archives of the user mailing list. If you really want to help, submit a patch to the Maven site (or this book). 2.7. Using the Maven Help Plugin Throughout the book, we will be introducing Maven plugins and talking about Maven Project Object Model (POM) files, settings files, and profiles. There are going to be times when you need a tool to help you make sense of some of the models that Maven is using and what goals are available on a specific plugin. The Maven Help plugin allows you to list active Maven profiles, display an effective POM, print the effective settings, or list the attributes of a Maven plugin. NOTE For a conceptual overview of the POM and plugins, see Chapter 3. The Maven Help plugin has four goals. The first three goals—active-profiles, effective-pom, and effective-settings— describe a particular project and must be run in the base directory of a project. The last goal—describe—is slightly more complex, showing you information about a plugin or a plugin goal. The following commands provide some general information about the four goals:
📄 Page
15
help:active-profiles Lists the profiles (project, user, global) that are active for the build. help:effective-pom Displays the effective POM for the current build, with the active profiles factored in. help:effective-settings Prints out the calculated settings for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings. help:describe Describes the attributes of a plugin. This need not run under an existing project directory. You must give at least the groupId andartifactId of the plugin you wish to describe. 2.7.1. Describing a Maven Plugin Once you start using Maven, you'll spend most of your time trying to get more information about plugins. You'll want to know: How do plugins work? What are the configuration parameters? What are the goals? The help:describe goal is something you'll use very frequently to retrieve this information. With the plugin parameter, you can specify a plugin you wish to investigate, passing in either the plugin prefix (e.g., maven-help-plugin as help) or the groupId:artifact[:version], where version is optional. For example, the following command uses the Help plugin's describe goal to print out information about the Maven Help plugin: $ mvn help:describe -Dplugin=help ... Group Id: org.apache.maven.plugins Artifact Id: maven-help-plugin Version: 2.0.1 Goal Prefix: help Description: The Maven Help plugin provides goals aimed at helping to make sense out of the build environment. It includes the ability to view the effective POM and settings files, after inheritance and active profiles have been applied, as well as a describe a particular plugin goal to give usage information. ... Executing the describe goal with the plugin parameter prints out the Maven coordinates for the plugin, the goal prefix, and a brief description of the plugin. Although this information is helpful, you'll usually be looking for more detail than this. If you want the Help plugin to print a full list of goals with parameters, execute the help:describe goal with the parameter full as follows: $ mvn help:describe -Dplugin=help -Dfull ... Group Id: org.apache.maven.plugins Artifact Id: maven-help-plugin Version: 2.0.1 Goal Prefix: help Description: The Maven Help plugin provides goals aimed at helping to make sense out of the build environment. It includes the ability to view the effective POM and settings files, after inheritance and active profiles have been
📄 Page
16
applied, as well as a describe a particular plugin goal to give usage information. Mojos: =============================================== Goal: 'active-profiles' =============================================== Description: Lists the profiles which are currently active for this build. Implementation: org.apache.maven.plugins.help.ActiveProfilesMojo Language: java Parameters: ----------------------------------------------- [0] Name: output Type: java.io.File Required: false Directly editable: true Description: This is an optional parameter for a file destination for the output of this mojo...the listing of active profiles per project. ----------------------------------------------- [1] Name: projects Type: java.util.List Required: true Directly editable: false Description: This is the list of projects currently slated to be built by Maven. ----------------------------------------------- This mojo doesn't have any component requirements. =============================================== ... remove the other goals ... This option is great for discovering all of a plugin's goals as well as their parameters. But sometimes this gives you far more information than you need. To get information about a single goal, set the mojo parameter as well as the plugin parameter. The following command lists all of the information about the Compiler plugin's compile goal: $ mvn help:describe -Dplugin=compiler -Dmojo=compile -Dfull NOTE What's a Mojo? In Maven, a plugin goal is known as a Mojo. 2.8. About the Apache Software License Apache Maven is released under the Apache License, version 2.0. If you want to read this license, you can look at${M2_HOME}/LICENSE.txt or read it on the Open Source Initiative's web site at http://www.opensource.org/licenses/apache2.0.php. Chances are good that, if you are reading this book, you are not a lawyer. If you are wondering what the Apache License, version 2.0 means, the Apache Software Foundation has assembled a very helpful Frequently Asked Questions (FAQ) page about the license, available here: http://www.apache.org/foundation/licence-FAQ.html. Here's the answer to the frequently asked question "I am not a lawyer. What does it all mean?": [This license] allows you to: • Freely download and use Apache software, in whole or in part, for personal, company internal, or commercial purposes; • Use Apache software in packages or distributions that you create.
📄 Page
17
It forbids you to: • Redistribute any piece of Apache-originated software without proper attribution; • Use any marks owned by the Apache Software Foundation in any way that might state or imply that the Foundation endorses your distribution; • Use any marks owned by the Apache Software Foundation in any way that might state or imply that you created the Apache software in question. It requires you to: • Include a copy of the license in any redistribution you may make that includes Apache software; • Provide clear attribution to the Apache Software Foundation for any distributions that include Apache software. It does not require you to: • Include the source of the Apache software itself, or of any modifications you may have made to it, in any redistribution you may assemble that includes it; • Submit changes that you make to the software back to the Apache Software Foundation (though such feedback is encouraged). This ends the installation information. The next part of the book contains Maven examples.
📄 Page
18
Part 2: Maven by Example The first Maven book was Maven: A Developer's Notebook (O'Reilly). That book introduced Maven in a series of steps via a conversation between you and a colleague who already knew how to use Maven. The idea behind the (now-retired) Developer's Notebook series was that developers learn best when they are sitting next to other developers and going through the same thought processes, learning to code by doing and experimenting. Although the series was successful, the Notebook format had limitations. Notebooks were designed to be "goal-focused" books that take you through a series of steps to achieve very specific goals. By contrast, larger reference books provide comprehensive material that covers the entirety of the topic. If you read Maven: A Developer's Notebook, you'll learn how to create a simple project or a project that creates a WAR from a set of source files. But if you want to find out the specifics of something like the Assembly plugin, you'll hit an impasse. Because there is currently no well-written reference material for Maven, you have to hunt through plugin documentation on the Maven web site or cull from a series of mailing lists. Once you really dig into Maven, you end up reading through thousands of HTML pages on the Maven site written by hundreds of developers, each with a different idea of what it means to document a plugin. Despite the best efforts of well-meaning volunteers, reading through plugin documentation on the Maven site is frustrating at best, and at worst, it's a reason to abandon Maven. Quite often, Maven users get stuck because they just can't find an answer. This lack of an authoritative (or definitive) reference manual has held Maven back for a few years, and it has been something of a dampening force on Maven adoption. With Maven: The Definitive Guide, we intend to change that situation by providing a comprehensive reference in Part 3. In Part II, we're preserving the narrative progression of a Developer's Notebook; it is valuable material that helps people learn Maven by example. Thus, here we "introduce by doing," and in Part 3, we fill in the blanks and dig into the details. Where Part 3 might use a reference table and a program listing detached from an example project, Part II is motivated by real examples. After reading this part, you should have everything you need to start using Maven. You might need to refer to Part 3 only when you start customizing Maven by writing custom plugins or when you want more detail about specific plugins.
📄 Page
19
Chapter 3. A Simple Maven Project Introduction Creating a Simple Project Building a Simple Project Simple Project Object Model Core Concepts Summary 3.1. Introduction In this chapter, we introduce a simple project created from scratch using the Maven Archetype plugin. This elementary application provides us with the opportunity to discuss some core Maven concepts while you follow along with the development of the project. Before you can start using Maven for complex, multimodule builds, we have to start with the basics. If you've used Maven before, you'll notice that it does a good job of taking care of the details. Your builds tend to "just work," and you only really need to dive into the details of Maven when you want to customize the default behavior or write a custom plugin. However, when you do need to dive into the details, a thorough understanding of the core concepts is essential. This chapter aims to introduce you to the simplest possible Maven project and then presents some of the core concepts that make Maven a solid build platform. After reading it, you'll have an fundamental understanding of the build lifecycle, Maven repositories, dependency management, and the Project Object Model (POM). 3.1.1. Downloading This Chapter's Example This chapter develops a very simple example that will be used to explore core concepts of Maven. If you follow the steps as described, you shouldn't need to download the examples to recreate the code produced by Maven. We will be using the Maven Archetype plugin to create this simple project, and in this chapter we won't modify the project in any way. If you would prefer to read this chapter with the final example source code, the example project may be downloaded with the book's example code at http://www.sonatype.com/book/mvn-examples- 1.0.zip or http://www.sonatype.com/book/mvn-examples-1.0.tar.gz. Unzip this archive in any directory, and then go to the ch03/directory. There you will see a directory named simple/, which contains the source code for this chapter. If you wish to follow along with the example code in a web browser, go to http://www.sonatype.com/book/examples-1.0 and click on the ch03/ directory. 3.2. Creating a Simple Project To start a new Maven project, use the Maven Archetype plugin from the command line: $ mvn archetype:create -DgroupId=org.sonatype.mavenbook.ch03 \ -DartifactId=simple \ -DpackageName=org.sonatype.mavenbook [INFO] Scanning for projects... [INFO] Searching repository for plugin with prefix: 'archetype'. [INFO] artifact org.apache.maven.plugins:maven-archetype-plugin: checking for \ updates from central [INFO] ----------------------------------------------------------------------- [INFO] Building Maven Default Project [INFO] task-segment: [archetype:create] (aggregator-style) [INFO] -------------------------------------------------------------------- [INFO] [archetype:create] [INFO] artifact org.apache.maven.archetypes:maven-archetype-quickstart: \ checking for updates from central [INFO] Parameter: groupId, Value: org.sonatype.mavenbook.ch03 [INFO] Parameter: packageName, Value: org.sonatype.mavenbook [INFO] Parameter: basedir, Value: /Users/tobrien/svnw/sonatype/examples [INFO] Parameter: package, Value: org.sonatype.mavenbook [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: artifactId, Value: simple [INFO] * End of debug info from resources from generated POM * [INFO] Archetype created in dir: /Users/tobrien/svnw/sonatype/examples/simple
📄 Page
20
mvn is the Maven 2 command. archetype:create is called a Maven goal. If you are familiar with Apache Ant, a Maven goal is analogous to an Ant target; both describe a unit of work to be completed in a build. The -Dname=value pairs are arguments that are passed to the goal and take the form of -D properties, similar to the system property options you might pass to the Java Virtual Machine via the command line. The purpose of the archetype:create goal is to quickly create a project from an archetype. In this context, an archetype is defined as "an original model or type after which other similar things are patterned; a prototype."[2] A number of archetypes are available in Maven for anything from a simple Swing application to a complex web application. In this chapter, we are going to use the most basic archetype to create a simple skeleton starter project. The plugin is the prefix archetype, and the goal is create. [2] The American Heritage Dictionary of the English Language Once we've generated a project, take a look at the directory structure Maven created under the simple directory: simple/<-- (1) simple/pom.xml<-- (2) /src/ /src/main/<-- (3) /main/java /src/test/<-- (4) /test/java This generated directory adheres to the Maven Standard Directory Layout. We'll get into more details later in this chapter, but for now, let's just try to understand these few basic directories: (1) The Maven Archetype plugin creates a directory that matches the artifactId. Simple. This is known as the project's base directory. (2) Every Maven project has what is known as a Project Object Model (POM) in a file named pom.xml. This file describes the project, configures plugins, and declares dependencies. (3) Our project's source code and resources are placed under src/main. In the case of our simple Java project, this will consist of a few Java classes and some properties files. In another project, this could be the document root of a web application or configuration files for an application server. In a Java project, Java classes are placed in src/main/java, and classpath resources are placed in src/main/resources. (4) Our project's test cases are located in src/test. Under this directory, Java classes such as JUnit or TestNG tests are placed insrc/test/java, and classpath resources for tests are located in src/test/resources. The Maven Archetype plugin generated a single class org.sonatype.mavenbook.App, which is a 13-line Java class with a static main function that prints out a message: package org.sonatype.mavenbook; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } } The simplest Maven archetype generates the simplest possible program: a program that prints "Hello World!" to standard output. 3.3. Building a Simple Project Once you have created the project with the Maven Archetype plugin by following the directions from the previous section (Section 3.2") you will want to build and package the application. To do so, run mvn install from the directory that contains the pom.xml: $ mvn install [INFO] Scanning for projects... [INFO] ------------------------------------------------------- [INFO] Building simple [INFO] task-segment: [install] [INFO] -------------------------------------------------------