Maven 2 Overview

 

Install

* Download Maven, e.g. apache-maven-2.2.1-bin.zip, from Maven download site: http://maven.apache.org/download.html
* Unzip content into a local directory, e.g. C:\prog
* Create an environment variable called MAVEN_HOME and point it to where maven was unzipped, e.g. C:\prog\apache-maven-2.2.1
* Add %MAVEN_HOME%\bin to PATH
* Run mvn -v to verify install

mvn -v
Apache Maven 2.2.1 (r801777; 2009-08-06 15:16:01-0400)
Java version: 1.6.0_25
Java home: C:\Program Files\Java\jdk1.6.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7" version: "6.1" arch: "amd64" Family: "windows"

Overview

Default Local Repository

* Default local repository: home_dir/.m2/repository, e.g. C:\Users\jli\.m2\repository

* Local repository can be configured in conf/settings.xml file:

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

Life Cycle Phases

validate, generate-sources, process-sources, generate-resources, process- resources, compile, process-classes, generate-test-sources, process-test- sources, generate-test-resources, process-test-resources, test-compile, test, prepare-package, package, integration-test, verify, install, deploy.
* Commonly used: validate, compile, test, package, install, deploy, clean, site

Maven Plugins

* Phases are made of plugins which contain goals.
* Maven is a framework of orderly execution of plugin goals.
* See this post

Generate a List of Archetypes

Archetype list could be long. Here is simple way to get a list of all archetypes:
* Redirect output to a file

mvn archetype:generate > mvn_archetypes.txt
ctr-c to terminate

* Browse mvn_archetypes.txt for archetypes
* For example, sample Maven Webapp project archetype:

174: remote -> org.apache.maven.archetypes:maven-archetype-webapp (An archetype which contains a sample Maven Webapp project.)

Copy a Jar File to Local Repository

* For example, copy Oracle ojdbc6.jar file to local repository:

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.2.0 -Dpackaging=jar -Dfile="C:\downloads\jdbc\ojdbc6.jar"

Maven Help

# List help goals
mvn help:help

# Print plugin info
mvn help:describe -Dplugin=compiler

# Print plugin info defail
mvn help:describe -Dplugin=compiler -Ddetail

Site Report

mvn site

Resources

* A resource is a file that is used at run time but does not require compilation. For example, log4j.properties file.

Project Dependencies

* Can manage both internal (i.e. your projects) and external dependencies

Project Scope

* compile:
– default scope
– available in all (compilation, runtime, test) classpaths
– packaged
* provided:
– available in compilation classpath only
not packaged
* runtime:
– available in runtime classpath only
– not needed for compilation
not packaged
* test:
– available in test classpath only
– not needed for either compilation nor runtime
* system:
– like provided but you must provide systempath element

Dependency Version Range

* (,) exclusive
* [,] inclusive
* Greater or equal to 3.8 but less than 4.0

<version>[3.8,4.0)</version>

* No higher than 3.8, lower versions are ok:

<version>[,3.8]</version>

dependencyManagement

* Different from dependencies element.
* Used in parent project to specify a version number (like an env variable)
* Allows child project to omit specifying version. For example:
– Parent pom:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.sonatype.mavenbook</groupId>
    <artifactId>a-parent</artifactId>
    <version>1.0.0</version>
    ...
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.2</version>
                <scope>runtime</scope>
            </dependency>
            ...
            <dependencies>

– Child pom:

<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.sonatype.mavenbook</groupId>
        <artifactId>a-parent</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>project-a</artifactId>
    ...
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</project>

Project Coordinates

* groupId:
– Similar to Java package
– Uses dot notation
– For example: org.apache.maven
* artifactId:
– Similar to Java class
– Do not use dot notation
* version
* classifier:
– Less used
– Used to differentiate different builds (e.g. Java 1.4 build vs Java 6 build) based on same codes

Project Inheritance

* Child project inherits all properties from parent project:
– identifiers (at least one of groupId or artifactId must be overridden.)
– dependencies
– developers and contributors
– plugin lists
– reports lists
– plugin executions (executions with matching ids are merged)
– plugin configuration
* Child pom can override parent pom
* To view an effective, i.e. merged, pom:

mvn help:effective-pom

Group Dependencies

* Group common dependencies into a shared project
* For example, put shared dependencies, e.g. hiberntae, spring, and mysql, in a single POM project:

<project>
    <groupId>org.sonatype.mavenbook</groupId>
    <artifactId>persistence-deps</artifactId>
    <version>1.0</version>
    <packaging>pom</packaging>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>${hibernateVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>${hibernateAnnotationsVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-hibernate3</artifactId>
            <version>${springVersion}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysqlVersion}</version>
        </dependency>
    </dependencies>
    <properties>
        <mysqlVersion>(5.1,)</mysqlVersion>
        <springVersion>(2.0.6,)</springVersion>
        <hibernateVersion>3.2.5.ga</hibernateVersion>
        <hibernateAnnotationsVersion>3.3.0.ga</hibernateAnnotationsVersion>
    </properties>
</project>

* Now declare a shared project dependency in project POM:

<project>
    <description>This is a project requiring JDBC</description>
    ...
    <dependencies>
        ...
        <dependency>
            <groupId>org.sonatype.mavenbook</groupId>
            <artifactId>persistence-deps</artifactId>
            <version>1.0</version>
            <type>pom</type>
        </dependency>
    </dependencies>
</project>

Inheritance or Multi-Module Composition

* In inheritance, child project inherits all values from parent.
* In multi-moduel, projects are simply grouped together. No parent-child relationship implied.
* See this post on how to setup multi-module projects.

The Build Lifecycle

* Consists of a sequence of named phases to produce a set of goals
* Default goals
– clean
– default (aka build)
– site: produce a web site files

Clean Lifecycle

* pre-clean
* clean: deletes build directory
* post-clean

Default Lifecycle

* validate: Validate the project is correct and all necessary information is available to complete a build

Sources

* generate-sources: Generate any source code for inclusion in compilation
* process-sources: Process the source code, for example to filter any values

Resources

* generate-resources: Generate resources for inclusion in the package
* process-resources: Copy and process the resources into the destination directory, ready for packaging

* compile: Compile the source code of the project
* process-classes: Post-process the generated files from compilation, for example to do bytecode enhancement on Java classes

Test

* generate-test-sources: Generate any test source code for inclusion in compilation
* process-test-sources: Process the test source code, for example to filter any values
* generate-test-resources: Create resources for testing
* process-test-resources: Copy and process the resources into the test destination directory
* test-compile: Compile the test source code into the test destination directory
* test: Run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed

Package

* prepare-package: Perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package (coming in Maven 2.1+)
* package: Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR

Integration Test

* pre-integration-test: Perform actions required before integration tests are executed. This may involve things such as setting up the required environment
* integration-test: Process and deploy the package if necessary into an environment where integration tests can be run
* post-integration-test: Perform actions required after integration tests have been executed. This may include cleaning up the environment
* verify: Run any checks to verify the package is valid and meets quality criteria

Install and Deploy

* install: Install the package into the local repository, for use as a dependency in other projects locally
* deploy: Copies the final package to the remote repository for sharing with other developers and projects (usually only relevant during a formal release)

Site Lifecycle

* pre-site
* site
* post-site
* site-deploy

Packaging Specific Lifecycles

* pom: simplest packaging type
* jar: default packaging type
* maven-plugin: generate a descriptor file and perform some modifications to the repository data in addition to jar:
– plugin:descriptor,
– plugin:addPluginArtifactMetadata
– plugin:updateRegistry
* ejb
* war
* ear
* Others

Common Lifecycle Goals

Process Resources

* Process resources in the ${basedir}/src/main/resources directory
* Perform token replacement
* Copy resource to output directory as defined by the ${project.build.outputDirectory}, which defaults to ${basedir}/target/classes directory

Resource Filtering (Token Replacement)

* File to be filtered: src/main/resources/service.xml

<service>
    <!-- This URL was set by project version ${project.version} -->
    <url>${jdbc.url}</url>
    <user>${jdbc.username}</user>
    <password>${jdbc.password}</password>
</service>

* Property file: src/main/filters/default.properties

jdbc.url=jdbc:oracle:thin:@//myhost:1521/orcl
jdbc.username=scott
jdbc.password=tiger

* Specify filters in pom.xml:

<build>
    <filters>
        <filter>src/main/filters/default.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

* Run: mvn process-resources command
* Check service.xml in target\classes\META-INF directory:

<service>
    <!-- This URL was set by project version 1.0-SNAPSHOT -->
    <url>jdbc:oracle:thin:@//myhost:1521/orcl</url>
    <user>scott</user>
    <password>tiger</password>
</service>

Multiple Resource Directories

* Create a separate directory to contain command files:
src/main/command
* Create a command file in that directory:

@echo off
java -jar ${project.build.finalName}.jar %*

* Define a new resource:

        <resource>
            <filtering>true</filtering>
            <directory>${basedir}/src/main/command</directory>
            <includes>
                <include>run.bat</include>
                <include>run.sh</include>
            </includes>
            <targetPath>${basedir}</targetPath>
        </resource>

* Run: mvn process-resources command
* Check run.bat in the project root directory:

@echo off
java -jar guide-ide-eclipse-1.0-SNAPSHOT.jar %*

Compile

* Compile everything from src/main/java to target/classes
* Defaults to compliance with Java 1.3 source code and Java 1.1 JVM.
* Use specific source and target Java versions:

<project>
    ...
    <build>
        ...
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
        ...
    </build>
    ...
</project>

* Overriding default source diretory

<build>
    ...
    <sourceDirectory>src/java</sourceDirectory>
    <outputDirectory>classes</outputDirectory>
    ...
</build>

Sample Webapp Project

* Sample Maven webapp project

References

* Maven Getting Started Guide
* Maven: The Complete Reference
* Apache Maven 2 Effective Implementation By: Brett Porter; Maria Odea Ching

This entry was posted in maven. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.