LOADING...

加载过慢请开启缓存(浏览器默认开启)

loading

Overview

Convention over Configuration

Maven uses Convention  over Configuration , which means developers are not required to create build process themselves.

Following table shows the default values for project source code files, resource files and other configurations. Assuming, ${basedir}  denotes the project location.

Item Deafult
source code ${basedir}/src/main/java
Resources ${basedir}/src/main/resources
Tests ${basedir}/src/test
Complied byte code ${basedir}/target
distributable JAR ${basedir}/target/classes

POM

POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.companyname.project-group</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
</project>

Minimal requirements for a POM:

Sr.No. Node & Description
1 Project root
This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification.
2 Model version
Model version should be 4.0.0.
3 groupId
This is an Id of project’s group. This is generally unique amongst an organization or a project.
4 artifactId
This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact’s location within the repository.
5 version
This is the version of the project. Along with the groupId, It is used within an artifact’s repository to separate versions from each other.

Super POM

The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM , and contains values inherited by default.

An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom.

Build Life Cycle

A Build Lifecycle is a well-defined sequence of phases, which define the order in which the goals are to be executed. A typical Maven Build Lifecycle consists of the following sequence of phases:

Phase Handles Description
prepare-resources resource copying Resource copying can be customized in this phase.
validate Validating the information Validates if the project is correct and if all necessary information is available.
compile compilation Source code compilation is done in this phase.
Test Testing Tests the compiled source code suitable for testing framework.
package packaging This phase creates the JAR/WAR package as mentioned in the packaging in POM.xml.
install installation This phase installs the package in local/remote maven repository.
Deploy Deploying Copies the final package to the remote repository.

There are always pre and post phases to register goals , which must run prior to, or after a particular phase.
When Maven starts building a project, it steps through a defined sequence of phases and executes goals, which are registered with each phase.

Maven has the following three standard lifecycles:

  • clean
  • default(or build)
  • site

goal represents a specific task which contributes to the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation.

mvn clean dependency:copy-dependencies package

Here the clean phase will be executed first, followed by the dependency:copy-dependencies goal , and finally package phase will be executed.

Clean Lifecycle

When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases:

  • pre-clean
  • clean
  • post-clean

Maven clean goal (clean:clean) is bound to the clean  phase in the clean lifecycle.

We can customize this behavior by mentioning goals in any of the above phases of clean life cycle.

<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.companyname.project-group</groupId>
    <artifactId>project</artifactId>
    <version>1.0</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version> 1.1 </version>
                <executions>
                    <execution>
                        <id>id.pre-clean</id>
                        <phase>pre-clean</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>pre-clean phase</echo>
                            </tasks>
                        </configuration>
                    </execution>
                    <execution>
                        <id>id.clean</id>
                        <phase>clean</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>clean phase</echo>
                            </tasks>
                        </configuration>
                    </execution>
                    <execution>
                        <id>id.post-clean</id>
                        <phase>post-clean</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>post-clean phase</echo>
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

You can try tuning mvn clean command, which will display pre-clean and clean. Nothing will be executed for post-clean phase.

Default (or Build) Lifecycle

This is the primary life cycle of Maven and is used to build the application. It has the following 21 phases:

Sr.No. Lifecycle Phase & Description
1 validate
Validates whether project is correct and all necessary information is available to complete the build process.
2 initialize
Initializes build state, for example set properties.
3 generate-sources
Generate any source code to be included in compilation phase.
4 process-sources
Process the source code, for example, filter any value.
5 generate-resources
Generate resources to be included in the package.
6 process-resources
Copy and process the resources into the destination directory, ready for packaging phase.
7 compile
Compile the source code of the project.
8 process-classes
Post-process the generated files from compilation, for example to do bytecode enhancement/optimization on Java classes.
9 generate-test-sources
Generate any test source code to be included in compilation phase.
10 process-test-sources
Process the test source code, for example, filter any values.
11 test-compile
Compile the test source code into the test destination directory.
12 process-test-classes
Process the generated files from test code file compilation.
13 test
Run tests using a suitable unit testing framework (Junit is one).
14 prepare-package
Perform any operations necessary to prepare a package before the actual packaging.
15 package
Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR file.
16 pre-integration-test
Perform actions required before integration tests are executed. For example, setting up the required environment.
17 integration-test
Process and deploy the package if necessary into an environment where integration tests can be run.
18 post-integration-test
Perform actions required after integration tests have been executed. For example, cleaning up the environment.
19 verify
Run any check-ups to verify the package is valid and meets quality criteria.
20 install
Install the package into the local repository, which can be used as a dependency in other projects locally.
21 deploy
Copies the final package to the remote repository for sharing with other developers and projects.

There are few important concepts related to Maven Lifecycles, which are worth to mention:

  • When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute.
  • Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR).

Site Lifecycle

Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases:

  • pre-site
  • site
  • post-site
  • site-deploy

Build Profiles

What is Build Profile?

A Build profile is a set of configuration values, which can be used to set or override default values of Maven build.

Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are triggered in variety of ways. Profiles modify the POM at build time, and are used to give parameters different target environments.

Repositories

What is a Maven Repository?

Maven repository are of three types:

  • local
  • central
  • remote

Local Repository

Maven local repository is a folder location on your machine. It gets created when you run any maven command for the first time.

Maven local repository keeps your project’s all dependencies (library jars, plugin jars etc.). When you run a Maven build, then Maven automatically downloads all the dependency jars into the local repository. It helps to avoid references to dependencies stored on remote machine every time a project is build.

Central Repository

Maven central repository is repository provided by Maven community. It contains a large number of commonly used libraries.
When Maven does not find any dependency in local repository, it starts searching in central repository using following URL(https://repo1.maven.org/maven2/).

Remote Repository

Maven provides concept of Remote Repository , which is developer’s own custom repository containing required libraries or other project jars.

Maven Dependency Search Sequence

When we execute Maven build commands, Maven starts looking for dependency libraries in the following sequence:

  • Step 1: Search dependency in local repository, if not found, move to step 2 else perform the further processing.
  • Step 2: Search dependency in central repository, if not found and remote repository/repositories is/are mentioned then move to step 4. Else it is downloaded to local repository for future reference.
  • Step 3: If a remote repository has not been mentioned, Maven simply stops the processing and throws error (Unable to find dependency).
  • Step 4: Search dependency in remote repository or repositories, if found then it is downloaded to local repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find dependency).

Plugins

What are Maven Plugins?

Maven is actually a plugin execution framework where every task is actually done by plugins.

Plugin Types

Maven provided the following two types of Plugins:

  • Build plugins: They execute during the build process and should be configured in the <build/> element of pom.xml.
  • Reporting plugins: They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.

Creating Project

Maven uses archetype plugins to create projects. To create a simple java application, we’ll use maven-archetype-quickstart plugin.

mvn archetype:generate \
    -DgroupId=com.companyname.bank \
    -DartifactId=consumerBanking \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DinteractiveMode=false

External Dependencies

What happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency.

<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.companyname.bank</groupId>
    <artifactId>consumerBanking</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <name>consumerBanking</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>ldapjdk</groupId>
            <artifactId>ldapjdk</artifactId>
            <scope>system</scope>
            <version>1.0</version>
            <systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath>
        </dependency>
    </dependencies>
</project>

Snapshots

What is SNAPSHOT?

SNAPSHOT is a special version that indicates a current development copy. Unlike regular versions, Maven checks for a new SNAPSHOT version in a remote repository for every build.

Manage Dependencies

Transitive Dependencies Discovery

With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies.

Sr.No. Feature & Description
1 Dependency mediation
Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used.
2 Dependency management
Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced.
3 Dependency scope
Includes dependencies as per the current stage of the build.
4 Excluded dependencies
Any transitive dependency can be excluded using “exclusion” element. As example, A depends upon B and B depends upon C, then A can mark C as excluded.
5 Optional dependencies
Any transitive dependency can be marked as optional using “optional” element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C.

Dependency Scope

Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below:

Sr.No. Scope & Description
1 compile
This scope indicates that dependency is available in classpath of project. It is default scope.
2 provided
This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime.
3 runtime
This scope indicates that dependency is not required for compilation, but is required during execution.
4 test
This scope indicates that the dependency is only available for the test compilation and execution phases.
5 system
This scope indicates that you have to provide the system path.
6 import
This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM’s <dependencyManagement> section.