Maven Basics

What is maven?

Maven is basically a dependency management tool for java projects. It also offers other important features like distribution management, building project locally or at remote server, packaging of project etc.

Why maven?

Following processes become easy when we use maven for java project:

1) Building projects locally or at remote server with simple configurations defined in an XML called pom.xml

2) Managing dependencies in a single project as well as across multiple projects(defined as modules in pom xml) with one parent project

3) Packaging of project in jar,war or ear formats

4) Distributing projects to the repository ,for others to use

5) Maintain versioning of projects like snapshot and release versions

6) Almost all commonly used frameworks like Spring, log4j, hibernate etc .are available as maven dependencies and hence can be easily added to project

How maven works?

Maven works with the concept of central repository. All the required dependencies in the form of jars are located at some central location. The default location is : https://repo.maven.apache.org/maven2/. This location can be changed if you have your own central repository server. The necessary changes should be done in settings.xml under ‘servers’ and ‘mirrors’ tag(details are discussed later). If you have a project whose jar you wish to distribute, you should upload version (usually either snapshot or release)of it in your central repository(Distribution details explained later).

The benefit of central repository is that multiple developers working on same project have the same jars with same version. In the absence of maven, each developer will download the jar on the local machine and use it in the project which might create discrepancies. Also, it becomes very easy to distribute the updated jars with your peers by simply uploading it into central repository.

How to install maven?

The installation details are mentioned at the official web site : http://maven.apache.org/install.html

Configuration Settings in maven:

The global settings in maven are defined in settings.xml which can be found at location: ${maven.home}/conf/settings.xml.

This settings.xml file provides configuration for all Maven users on a machine (assuming they’re all using the same Maven installation).

In the absence of any user specific settings.xml, this file is taken up as default settings option.

User can specify his/her own settings.xml which will then should be placed in ${user.home}/.m2 folder.

This xml has various options of configurations like:

1) localRepository: Define path of your local repository to point to. Default is ${user.home}/.m2/repository

2) interactiveMode: true/false value to decide if maven should attempt to interact with user. Defaults to true.

3) usePluginRegistry: true/false value to decide if Maven should use the ${user.home}/.m2/plugin-registry.xml file to manage plugin versions, defaults to false.

4) offline:true if this build system should operate in offline mode, defaults to false. If we set offline to true, maven looks for the dependencies in local repository cache(${user.home}/.m2/repository). This element is useful for build servers which cannot connect to a remote repository, either because of network setup or security reasons. But if the current project refers to the artifacts which are not yet present in local repository, building the project will fail. Offline mode can also be turned on while running maven project with command like ‘mvn -o install’ or ‘mvn –offline’.

5) pluginGroups: This element contains a list of pluginGroup elements, each contains a groupId. The list is searched when a plugin is used and the groupId is not provided in the command line. This list automatically contains org.apache.maven.plugins and org.codehaus.mojo.

6) servers: Lists the server which are used as repositories. The list of repositories can be mentioned in pom.xml, but this tag includes extra information about servers like username,password etc which should not be distributed along with the pom.xml

Note:You should either specify username/password OR privateKey/passphrase, since these pairings are used together.

This server can then be referred in pom.xml under ‘repository’ tag.

Note: Here,the repository id should match with the server id mentioned in settings.xml

7) mirrors: Defines the mirror of the servers defined.

Some reasons to use a mirror are:

  • There is a synchronized mirror on the internet that is geographically closer and faster
  • You want to replace a particular repository with your own internal repository which you have greater control over
  • You want to run a repository manager to provide a local cache to a mirror and need to use its URL instead

8) proxies: Defines the proxy server settings.

9) profiles : Defines various profiles for different circumstances and environments like for different OS, different jdk versions etc. User can define various options for which defined profile gets activated.

10) activeProfiles: Any profile id defined as an activeProfile will be active, regardless of any environment settings.

What are maven plugins?

While using maven, you will often come across with the term plugins. Plugins are the actual piece of code that performs specific action in maven project. These plugins are bundled as a jar file. Plugins can perform operations like : create jar files, create war files, compile code etc. Each goal in maven (like clean,install,deploy etc) are bundled in the form of plugins which are available at location http://repo1.maven.org/maven2/maven/. This location is by default pointed to when maven project is set up. If any user has his own plugins, he can point to it with settings.xml as mentioned above.

What is pom xml?

It’s the heart of maven because it describes the maven project.

Super POM:

The Super POM is Maven’s default POM. All POMs extend the Super POM unless explicitly set, meaning the configuration specified in the Super POM is inherited by the POMs you created for your projects. It’s located in maven-model-builder jar inside the maven distribution.

Project POM:

Each maven project has its own pom xml which should contain following minimum configuration:

1)modelVersion: Model version is the version of project descriptor your POM conforms to.It is always set to 4.0.0 in Maven 2 and 3, because, at present, there is no other model.

2)groupId: Its usually the organization name in reverse order like com.mycompany.app

3)artifactId: It’s the actual project name like first-app

4)version: It’s the version of the project like 1.0.0

<groupId>:<artifactId>:<version> defines your project’s fully qualified artifact name. For example : com.mycompany.app:first-app:1.0.0

Commonly required configurations in POM:

The commonly used configurations in pom.xml are packaging and distribution configurations:

Packaging:

The default packaging of any java project is ‘jar’ in maven. Other options are war,ejb,ear,pom and maven-plugin which can be defined in ‘packaging’ tag. But for packaging in form of zip,gz,tar we have to make some configuration. Let’s say you have to package your project as zip file, you can do so with maven’s maven-assembly-plugin. This plugin asks for a descriptor file which is an xml(usually named as your_project_name_assembly.xml). This assembly xml defines packaging options like format,file sets,output directory etc.

The assembly xml file would look like:

Distribution management:

In order to publish your jar file at central repository,’distributionManagement’ tag is used. This tag has two separate tags for release and snapshot versions to be deployed. The release versions are configured under ‘repository’ tag while snapshot versions are configured under ‘snapshotRepository’ tag.

 

 

Project variables:

For ease of maintenance and to avoid repeatability, user can define variables inside ‘properties’ tag which he is going to use throughout the pom xml. For example, in case of adding various spring modules as dependencies, we would refer same version number in each ‘dependency’ tag. Instead of it, we can define a variable like spring.version and use it everywhere as ${spring.version}. This allows user to change the version number (if required)easily at single location rather than changing the versions at multiple locations.

Dependencies:

Each java project is dependent on some external jars for it working. Maven makes it easy to handle these dependencies with easy configuration.

In the absence of maven, we have to search for specific jar with specific version on the net, download it and put it in the classpath. With maven, we just need to add single tag ‘dependency’ with mandatory details like groupId,artifactId and version. Maven then automatically downloads the jar for you and puts it into .m2 folder. The sequence in which these dependencies are defined in pom.xml matter when multiple dependencies internally refer to same dependency. For example, two dependencies ‘spring-core’ and ‘commons-httpclient’,both internally refer to ‘commons-logging’ but of different version. Whichever dependency is mentioned first ‘spring-core’ or ‘commons-httpclient’ ,corresponding version of ‘commons-logging’ is considered and another version is omitted.

Let’s consider ‘spring-core’ dependency is declared before ‘commons-httpclient’, 1.2 version of ‘commons-logging’ is considered while version 1.0.3 is omitted.

Now, let’s reverse the order of declaring the dependency and we can see that now version 1.0.3 is considered while version 1.2 is omitted.

What is project inheritance in maven?

A maven project can act as a parent project for multiple child projects.

In child project we can define what is our parent project with tag ‘parent’. Adding this tag in child project allows child project to use configurations in parent project like various properties,distribution options. This avoids repeating of configurations common to all child projects.

Consider you have a project with number of child projects. All these projects have the same distribution configuration.So, in such scenarios , instead of declaring the same distribution tag in all of the children pom xml, we can define it in parent pom and mention the name of parent in child project. Have a look at following sample parent and child pom xmls:

 

What is project aggregation in maven?

Similar to project inheritance, in project aggregation we define parent-child relationship but in parent pom xml. The child projects are called ‘modules’ and are defined in the parent pom xml. The major advantage of this type of parent-child structure is that ,each child might have some common dependencies,common configurations which we can defined in parent pom while each child can then have its own dependencies and configurations defined. This is also helpful while building various related project. Let’s say we have 10 modules which we wish to build, in normal scenario,we will have to build each project individually. But if we introduce a parent project,building that project will build all its child projects. The parent pom will then look like:

Build lifecycle in maven:

Default lifecycles:

Maven has following default build lifecycle phases:

1)validate – validate the project is correct and all necessary information is available

2)compile – compile the source code of the project

3)test – test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed

4)package – take the compiled code and package it in its distributable format, such as a JAR.

5)verify – run any checks on results of integration tests to ensure quality criteria are met

6)install – install the package into the local repository, for use as a dependency in other projects locally

7)deploy – done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

When any of the phase is invoked in maven,all the phases upto that phase are executed. For example,if I invoke mvn package, this will execute all previous phases from validate to package.

Difference between phase and goal in maven:

Maven has default phases and these phases have some goals bind to them. For example,a Java project can be compiled with the compiler-plugin’s compile-goal by running mvn compiler:compile. When a phase is run as mentioned earlier, all previous phases also run but we can run specific goal directly by invoking command with syntax  mvn [plugin-name]:[goal-name]. For example, we can install project locally with command mvn install:install.

Clean lifecycle in maven:

Clean lifecycle has three phases:

1)pre-clean

2)clean

3)post-clean

The Clean plugin’s clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. The clean:clean goal deletes the output of a build by deleting the build directory. If you haven’t customized the location of the build directory it will be the ${basedir}/target directory as defined by the Super POM.

How to change build directory of maven?

The default build directory in maven is ‘target’ folder located at basedir where basedir is the location of your project.

There are three ways you can change this directory:

1)Updating project pom.xml as

<project>

<build>

<outputDirectory>path/of/your/directory</outputDirectory>

</build>

</project>

This option can used when you wish to change build directory only for few projects,meaning you dont wish to change the setting at global level.

2)While preparing the package like war

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-war-plugin</artifactId>

<version>2.0</version>

<configuration>

<warName>your-app</warName>

<outputDirectory>path/of/your/directory</outputDirectory>

</configuration>

</plugin>

This option can be used when you wish to bundle your class files in particular folder in your distribution.

3)By defining profile

<profiles>

<profile>

<id>otherOutputDir</id>

<build>

<directory>path/of/your/directory</directory>

</build>

</profile>

</profiles>

This option can be used to set the directory at global level,meaning you have changed build directory for all maven projects.

 

 

 

 

Spread the love

2 thoughts on “Maven Basics”

Leave a Reply

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