Maven And Its Features

  • By
  • December 27, 2019
  • JAVA Programming
Maven And Its Features

Maven And Its Features

If you are a developer, you would recognize that one of the most repetitive aspects of application development is building or creating the application deployment artefact or deployment package. Every time you change something in the application, you need to rebuild the package. For a task this repetitive, you need to ensure that all the application code, resources, dependencies like libraries – self-created or 3rd party libraries, other project dependencies, interface packages, etc are put in the package so that you get a proper working application and don’t face application runtime issues. Also, some applications may be web-applications, others might be just library applications while some might be container-based applications. Each of these require a different set of compilation tools for generating the executable code, build tools for packaging and creating deployment artefact or test tools for executing the relevant unit test or checking the code quality. Maven is a powerful and versatile build automation tool that helps you in this critical step.

In this blog, I will give you a view of how Maven simplifies the build and packaging part of the development process.

We will understand the following aspects of Maven:

  • What is Maven
  • Maven’s Features
  • Maven Architecture
  • Maven Lifecycle, phases and goals

So, let’s get started.

What is Maven?

Maven is a tool that allows for software project management and also assists in understanding and exploring the project by providing an overview and visualization of the project.

Software Project Management is provided via managing the project’s build, providing a standard and simplified way of specifying and managing the resources, files, dependencies in the project and share the project’s output artefacts with other projects/applications.

Visualization of the project is provided via providing the project information, managing the reporting of the project and documentation of the project.

Maven Objectives

Project development is seldom a single person’s effort. Even if it is started by a single person, over a period of time there will be other people involved for enhancement, maintenance, bug-fixes, application understanding and analysis, project takeover or handover from the earlier owner to new one and so on. The point is that for the “others” to understand the project, maven provides a standard way to interpret how the project is organized, built, its dependencies, its output artefacts and aid his understanding via the maven project reports and documentation.

The primary goal is hence to allow a developer to understand the complete development effort in easiest and shortest way.

To achieve this, the following objectives are most important:

  • Easier Build Process
  • Have a Uniform Build System
  • Maintain quality project information
  • Provide best practices development guidelines
  • Allow transparent migration to new features

maven classes in pune

Easier Build Process

Though you would still need to control and configure the build process, the process of how to build and specifying and managing the project dependencies is highly simplified and standardized.

This in itself is a big step forward from the earlier state, where every project had a different way and command to build the project and also include the dependencies of the application during the build.

The benefits scale out a lot when you have multiple projects and multiple developers on those projects, but they need to understand only a single build process.

Also, when these projects are linked up to a Continuous Integration platform like Jenkins, the standardization of the tooling helps in quicker setup of the CI platform for continuous build, integration with other modules and testing of the modules. And in knowing if a development change is impacting the build of the other dependent projects.

Uniform Build System

Maven allows you to configure the build of the project using its project object model (POM). It also provides a set of plugins that are shared by all projects using Maven. These plugins allow to execute the steps in the build process executing the tasks that achieve the target of the build. These two features allow maven to provide a uniform build system and process. Once you know how one Maven project builds, you automatically know how all Maven projects build. This saves a developer a low of time and effort when trying to navigate and understand many projects.

Maintain quality project information

Maven provides a lot of useful project information, taken partly from your POM and other parts extracted from your project’s sources.

Some of the key project information that Maven can provide includes:

  • Change log document created directly from source control

This provides a direct from the source and up to date list of project changes. This is frequently required by the developer and the team owning the project.

  • Cross referenced sources

This is frequently required when we need reports. For example: test reports which cross-reference the source code line where the failure occurred, or the project document generated by the maven site report that cross references the source code.

  • List of mailing lists managed by the project

This allows us to create and manage subscription/unsubscription to the mailing list of the project. Mailing list is a great way to keep interested developers and users of the project in the loop and informed about the project.

  • Dependency list

This is the key feature of maven. Dependencies are artefacts that the project needs to build and run correctly. Maven manages the direct dependencies as configured by the developer and also the transitive dependencies (dependencies of the direct dependencies) that are automatically brought in by maven.

Maven can provide the information about what are the direct and transitive dependencies of the project along with the source of the dependencies and version information.

  • Unit test reports including coverage

Maven can automatically execute the unit test suite packaged with the project and provide the unit test report, the cross-referenced results linked to the source code and the test coverage of the project.

This is an incredibly powerful feature that allows the developer, the operations/project team and quality governance team to get a real time view of the quality of the code.

As Maven keeps improving and adds enhancements, the information provided keeps improving in the background transparent to the Maven users.

Other products can also integrate with Maven during the build process. They can provide their custom Maven plugins allowing their project information reported along with the standard information given by Maven. This is all still based on and configured in the POM.

e.g. the SonarQube product checks the project code quality and provides the code quality metrics, this can easily work along with Maven using custom SonarQube Maven plugins.

Best Practices Development Guidelines

Maven captures the best principles and practices of development and guides projects to adopt those in the project.

Some of the examples are:

  • Project directory structure layout

Maven suggests a guideline and keeps a project directory structure by default as an opinion. Once the structure is adopted, all the projects follow the same and it becomes easier to navigate any project.

  • Dependency scope declaration

Maven allows declaration of dependencies as per the scope of their use. Some dependencies are needed at compile time, some at runtime, some only during test execution. This allows us to include the dependencies only when needed instead of packaging them all the time.

e.g. Dependencies to mock an external interface call is required only during the test execution when we need a mocked-up test response to achieve the test results, but needs to be excluded when we have a production or actual environment where the call needs to go to the actual system.

  • Unit Test best practices

Specifying, configuring and execution of test cases is made simpler by maven by adopting some unit testing best practices like:

  • Keeping test source code in a separate, parallel source tree structure.
  • Using test case naming conventions to make locating and executing tests convenient
  • Have test case setup their own environment instead of changing and customizing the build to achieve the same for test preparation. That makes the build process simpler and standard and the test execution independent.
  • Maven assists in release and issue management project workflows

Transparent Migration to New Features

Maven clients can easily update their installations so that they can take advantage of any changes that have been made to Maven itself. This is transparent to the projects and the maven users.

Also, installation of new or updated Maven/third-party plugins is very trivial. In most cases this would not even be noticed by the developer.

Maven Features

Maven provides the following key features:

  • Simple project setup that follows best practices

Setting up a new project or module is completed in an instant.

  • Consistent usage across all projects

Since the tooling is the same across all projects, getting new developers acquainted with the same is simpler and does not require extra efforts

  • Superior dependency management

Dependencies can be easily specified. Automatic updating of dependencies by using only latest versions is possible. We can have closures of the dependency, transitive dependencies – project dependencies that have other dependencies of their own and which need to be part of the project during build/runtime. We also get the ability to specify compile-time, test, environment-specific and production dependencies.

  • Able to easily work with multiple projects at the same time
  • A large and growing repository of libraries and metadata to use out of the box, and arrangements in place with the largest Open Source projects for real-time availability of their latest releases
  • Extensible

Maven allows you write own extensions to the standard maven process via custom plugins, with the ability to easily write plugins in Java or scripting languages

  • Instant access to new features with little or no extra configuration
  • Ant tasks for dependency management and deployment outside of Maven
  • Model based builds

Maven is able to build any number of projects into predefined output types such as a JAR, WAR, or distribution based on metadata about the project, without the need to do any scripting in most cases.

  • Coherent site of project information

Using the same metadata as for the build process, Maven is able to generate a web site or PDF, and provides standard reports about the state of development of the project including any documentation you want.

  • Release management and distribution publication

Without much additional configuration, Maven will integrate with your source control system (such as Git) and manage the release of a project based on a certain tag. It can also publish this to a distribution location for use by other projects. Maven is able to publish individual outputs such as a JAR, an archive including other dependencies and documentation, or as a source distribution.

  • Dependency management

Maven encourages the use of a central repository of JARs and other dependencies. Maven comes with a mechanism that can be used to download any JARs required for building your project from a central JAR repository. This allows users of Maven to reuse JARs across projects and encourages communication between projects to ensure that backward compatibility issues are dealt with.

We can also have our own central repository created and used by our projects.

Maven Architecture

Maven Architecture ju

Maven Repositories

Maven utilizes the concept of repositories to store all the artifacts. These artefacts could be the project packages, maven plugins or packages, maven libraries or 3rd party libraries and plugins.

There is a local respository created on the device where the maven tool is executing. This is to store the local packages created that need to be installed when the maven build is executed.

There are remote repositories that are created on central servers that can be accessed by multiple developers and development environments where maven tool is used. This serves as a central storage of the packages that are generated and deployed by the developer community that access the remote repository. It also acts as a location from where the dependencies that are not present in the local repository can be downloaded from.

Maven provides a default central repository that is commonly used by developer community. This can be accessed at http://repo.maven.apache.org/maven2/

You could also setup an internal maven repository for an organization, which is very common as it reduces the download time to get the repository artefacts for the maven tool. It also allows the organization to control what maven projects and packages are authorized and available for use for the internal projects. Also in a corporate network, access to internet is restricted and downloading from maven central repository may not be acceptable for security, speed and bandwidth reasons.

You just need a server and have the required artefacts stored in the same structure as in the maven central repository.

Maven Configuration

Controlling maven configuration is achieved via:

  • Project configuration

This is project level configuration about the project build, deployment, documentation.

It is configured via the project pom.xml.

  • Parent configuration

Each project configuration (pom.xml) refers to a parent maven configuration that provides the defaults. This is provided by default by the maven Super pom, which is Maven’s default POM. All POMs extend the Super POM, so they inherit the default settings from there.

A snippet of the Super POM can be viewed at https://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Super_POM

But an organization can define its own defaults for their projects to inherit. These can be specified in their own parent POM and configure the projects to inherit from this parent POM, by specifying it as parent project in the project pom.xml.

  • User Configuration

The user specific maven configuration is provided in the maven settings.xml file located at ${user.home}/.m2/settings.xml.

You can configure the local repository location as below:

<settings>
  …
<localRepository>/path/to/local/repo/</localRepository>


</settings>

Configuring a remote repository is also possible, so that an organization’s or a team’s remote repository is configured

<repositories>
<repository>
<id>my-internal-site</id>
<url>http://myserver/repo</url>
</repository>
</repositories>

Many times access to the internet is controlled via proxies and proxy servers. These can be set in the settings.xml as below:

<proxies>
<proxy>
<active/>
<protocol/>
<username/>
<password/>
<port/>
<host/>
<nonProxyHosts/>
<id/>
</proxy>
</proxies>

Maven Lifecycle, Phases and Goals

Maven Lifecycle is the core concept that drives the simplicity of the tool. This is what helps the developer to learn only a small set of commands to automate the build process with the help of Java Course In Pune.

Lifecycle and its relationship with the other two core concepts of lifecycle phases and phase goals are what allow maven to have flexibility and extensibility.

A Build Lifecycle (e.g. default, clean, site) is made up of phases (e.g. validate, compile, test, package, verify, install, deploy, etc.) and a build phase is made up of plugin goals (e.g. resources, compile, test, jar, war, install, deploy, etc).

deploy

Maven Lifecycle

There are three built-in maven lifecycles: default, clean and site.

The default lifecycle manages the project deployment.

This is the lifecycle that is executed by default when no other option is provided to the maven project. So when we execute the “mvn” maven command in the project directory with the project pom.xml file, it executes this lifecycle to complete the project deployment.

The clean lifecycle manages the project cleaning.

In between the project deployment, we have the need to start afresh and clean up the project artefacts. This is achieved by the clean lifecycle. Executing the “mvn clean” maven command in the project directory with the project pom.xml file causes the cleanup action to be triggered to get the intermittent, target and output directories to be cleansed.

The site lifecycle manages the creation of the project’s site documentation.

Generating the project site documentation is achieved by the site lifecycle.

Executing the “mvn site” maven command in the project directory with the project pom.xml file triggers the documentation generation activity.

Maven Phases

Each of the build lifecycles described above, in turn, are defined and composed of a list of build phases. A build phase is like a stage/milestone in the lifecycle.

For example, the deployment lifecycle “default” is composed of:

Validate, compile, test, package, verify, install and deploy maven phases.

The lifecycle phases are executed sequentially to complete the lifecycle.

So for the example above for the “default” lifecycle, when the “mvn” command is used, Maven will first validate the project, then compile the sources, execute the test cases against the compiled classes, package the binaries (create jar/war artefacts), run the integration tests, verify the integration tests, install the verified package to the local repository and then finally deploy the installed package to the remote repository.

In case we need to run specific phases only, then we can provide these phase names as arguments to the maven “mvn” command as below:

“mvn install”

Executes all the earlier phases in order (validate, compile, test, package, verify) and then install the package to the local repository.

We could also combine two phases of different lifecycles to have a combination effect as below:

“mvn clean deploy”

This executes the cleanup activity before starting the deployment to the remote repository (executing the earlier steps in sequence and totality before deploy).

Maven Goals

A Maven Phase is a stage/milestone in the lifecycle, but to execute the steps to complete the stage maven would need the specific tasks to be followed and completed.

This is what Maven Goals do. The manner in which the specific task responsibility and requirement is carried out is defined in the maven goals.

Each build phase comprises of one or more maven plugin goals. Maven plugins are what contain the core execution steps of the build lifecycles and phases.

So, for example, a “package” phase might have ejb:ejb or jar:jar or rar:rar or war:war goal depending on the package type to be created (which is specified in the project pom).

To get a detailed mapping of the lifecycles to phases to plugin goals, refer to the maven documentation on lifecycle at:

https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

Default Lifecycle-Phase-Goal

Lifecycle Phase Plugin:Goal Details
default validate validate the project is correct and all necessary information is available.
initialize initialize build state, e.g. set properties or create directories.
generate-sources generate any source code for inclusion in compilation.
process-sources process the source code, for example to filter any values.
generate-resources ear:generate-application-xml generate resources for inclusion in the package.
process-resources resources:resources copy and process the resources into the destination directory, ready for packaging.
compile compiler: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.
generate-test-sources generate any test source code for inclusion in compilation.
process-test-sources resources:testResources 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 compiler:testCompile compile the test source code into the test destination directory
process-test-classes post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes. For Maven 2.0.5 and above.
test surefire:test run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
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. (Maven 2.1 and above)
package ejb:ejb or ejb3:ejb3 or jar:jar

or par:par or

rar:rar or war:war or ear:ear

take the compiled code and package it in its distributable format, such as a JAR.
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 including cleaning up the environment.
verify run any checks to verify the package is valid and meets quality criteria.
install install:install install the package into the local repository, for use as a dependency in other projects locally.
deploy deploy:deploy done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

 

 

Clean Lifecycle-Phase-Goal

Lifecycle Phase Plugin:Goal Details
clean pre-clean execute processes needed prior to the actual project cleaning
clean clean:clean remove all files generated by the previous build
post-clean execute processes needed to finalize the project cleaning

Site Lifecycle-Phase-Goal

Lifecycle Phase Plugin:Goal Details
site pre-site execute processes needed prior to the actual project site generation
site site:site generate the project’s site documentation
post-site execute processes needed to finalize the site generation, and to prepare for site deployment
site-deploy site:deploy deploy the generated site documentation to the specified web server

Sample Project

We shall continue with understanding maven via an actual project that has a database connection via hibernate in the next blog. Watch out for the same…

In Conclusion

I hope this blog from Java Classes In Pune would have helped you appreciate the benefits of Maven tool especially for Java application development. Also, you now understand where it fits and helps in your application development process. Hopefully you would also have grasped the key features of Maven and the concepts around it. Good luck using this knowledge in your application build and packaging process. Also lookout for my next blog that continues on the maven journey by explaining the Project Object Model pom.xml structure and an actual project implementation of maven.

Looking forward to your experiences and comments at Java Training In Pune.

Author: Kiran Tiwari

Designation: Software Trainer

Company:  Seven Mentor Pvt. Ltd.

kirru

 

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

Submit Comment

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

*
*