User Professor Hans Noodles
Professor Hans Noodles
Level 41

Part 4. The basics of Maven

Published in the Java Developer group
This material is part of the "Introduction to Enterprise Development" series. Previous articles: Part 4. The basics of Maven - 1Maven is a tool for managing and building projects — a Java programmer's helpful assistant. It makes life easier for developers at every stage of work: from creating the project structure and connecting the necessary libraries to deploying the product on the server. You'll have to use Maven when working with any framework. So, today let's take a look at its main functions and see how to use them.

Step-by-step installation of Maven

  1. First, we need to install Maven. Download it from this link.

  2. Next, unzip the downloaded archive and set the M2_HOME environment variable to the location of the unzipped archive. For example, C:\\Program Files\\maven\\

  3. To ensure that everything is installed, execute the following on the command line:

    mvn -version

  4. If the version information for Maven, Java, etc. is displayed, then everything is ready to go.

  5. Now open IntelliJ IDEA and create a new project. In the first window, select Maven:

    Part 4. The basics of Maven - 2
  6. Click "Next" and fill out the window that appears:

    Part 4. The basics of Maven - 3
  7. Then, as usual, create a project wherever you want.

    After the project has been created, take note of its structure:

    Part 4. The basics of Maven - 4
This is the standard structure of a Maven project:
  • the src/main/java folder contains the Java classes
  • the src/main/resources folder contains the resources used by the application (HTML pages, images, style sheets, etc.)
  • the src/test folder is for tests
Also pay attention to the file called pom.xml. This is the main file for managing Maven. The entire project description is contained here. There is not too much information at the moment, but we will add it now.

Managing dependencies in Maven

You may have come across the phrase "dependency manager". Maven knows how to manage dependencies. Thanks to Maven, you don't have to spend a lot of time searching the Internet for a required library, downloading it, and then connecting it to your project. Instead, you just add the required library to the list of dependencies in Maven.

Dependencies are specified in the dependencies node of the pom.xml file

Let's say you need the Apache Commons IO library in your project in order to simplify working with files. To add a library, we write five lines in pom.xml:

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>
Now your pom.xml file should look like this:

  <?xml version="1.0" encoding="UTF-8"?>
<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>example.com</groupId>
   <artifactId>example</artifactId>
   <version>1.0-SNAPSHOT</version>

   <dependencies>
       <dependency>
           <groupId>commons-io</groupId>
           <artifactId>commons-io</artifactId>
           <version>2.6</version>
       </dependency>
   </dependencies>
</project>
After that, allow IntelliJ IDEA to import the dependency (a dialog should appear in the lower right corner). Now the library is ready to use:

import org.apache.commons.io.FileUtils;

import java.io.File;

public class TestMaven {
   public static void main(String[] args) {
       File tempDirectory = FileUtils.getTempDirectory();
   }
}
All subsequent dependencies must also be written inside the <dependencies> tag. You may be wondering how to find out the information about the library that you need to indicate inside the <dependency> tag. That's easy. Three parameters are always need to be set: "groupId", "artifactId" and "version". There are two ways to determine these parameters:
  1. On the library's website. If we need the Apache Commons IO library, we go to the official website and select the "Dependency Information" tab. All the necessary information is here — you can simply copy it and add it to the <dependencies> node.

  2. In a Maven repository. Enter "apache commons io" in the search bar and you'll see all available versions of the library. After selecting the correct one, simply copy the following:

    
    <dependency>
               <groupId>commons-io</groupId>
               <artifactId>commons-io</artifactId>
               <version>2.6</version>
           </dependency>
    

    and add it to your pom.xml.

Types of Maven repositories

It's worthwhile for us to mention Maven repositories again, because we actually have two of them: a remote (central) repository and a local (on your computer) repository. All libraries that you add to your projects are saved in the local repository. When Maven adds a required dependency to a project, it first checks whether the library already exists in the local repository. It accesses the remote repository only if it does not find the library locally. As you can see, you can use Maven to add dependencies, but this isn't all it can do.

Building a Java project using Maven

This capability may seem pointless to a beginner. Why do we need this if we have an IDE? Let me explain. First, the server where you have to build your application may have neither a development environment nor a graphical interface. Second, on large projects, Maven does a better job of building the project. So without further adieu, we'll consider the process of building an application using Maven.

Phases

The process of building an application is known a Maven project's life cycle, and it consists of phases. You can look at them in IDEA by clicking Maven > example > Lifecycle in the upper right corner: Part 4. The basics of Maven - 5As you can see, there are 9 phases:
  1. clean — removes all compiled files from the target directory (the place where finished artifacts are saved)
  2. validate — checks whether all the information required to build the project is present
  3. compile — compiles source code files
  4. test — starts tests
  5. package — packages compiled files (in a JAR, WAR, etc. archive)
  6. verify — checks whether the packaged file is ready
  7. install — places the package in the local repository. Now it can be used by other projects as an external library
  8. site — creates project documentation
  9. deploy — copies the built archive to the remote repository
All phases are performed sequentially: for example, the fourth phase cannot be started until phases 1-3 are completed. There are two ways to start a phase:
  • through the command line:

    mvn package

    Part 4. The basics of Maven - 6
  • using IntelliJ IDEA:

    Part 4. The basics of Maven - 7

    Before the package phase starts, the validate, compile, and test phases are performed. The clean phase is an exception. It's a good idea to run this phase before each build of the project. You can list multiple phases, separating them with spaces:

    mvn clean package.

Also, each phase has pre- and post-phases: for example, pre-deploy, post-deploy, pre-clean, post-clean, etc. but they are used quite rarely. In addition, each phase has goals. Standard goals are set by default. Additional goals are added by Maven plugins. Sometimes during a phase, you may need to perform additional functions. There are Maven plugins for this. A list of official plugins can be found on the Maven website. But you should know that there are many custom plugins that can be found on third-party websites. And of course, if some exotic need arises, you can always write a custom plug-in yourself. Part 4. The basics of Maven - 8

Plugins

To add a Maven plugin to the project, we need to add its description to the pom.xml file, using <build> and <plugins> tags, similar to how we added dependencies. For example, suppose we need a plugin to verify that we are using the latest version of all of our external libraries. After a bit of searching the Internet, you could find this plugin and instructions on how to use it. Let's set the groupId, artifactId and version. We'll indicate what goals the plugin must fulfill and at what phase. In our case, the dependency check in the current pom.xml is set to happen during the validate phase. Now our pom.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<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>example.com</groupId>
   <artifactId>example</artifactId>
   <version>1.0-SNAPSHOT</version>

   <build>
       <plugins>
           <plugin>
               <groupId>com.soebes.maven.plugins</groupId>
               <artifactId>uptodate-maven-plugin</artifactId>
               <version>0.2.0</version>
               <executions>
                   <execution>
                       <goals>
                           <goal>dependency</goal>
                       </goals>
                       <phase>validate</phase>
                   </execution>
               </executions>
           </plugin>
       </plugins>
   </build>

   <dependencies>
       <dependency>
           <groupId>commons-io</groupId>
           <artifactId>commons-io</artifactId>
           <version>2.6</version>
       </dependency>
   </dependencies>
</project>
We could continue to work on our project. But let's try changing the version of Apache Commons IO to 2.0 and building the project. We'll get

[ERROR] Failed to execute goal com.soebes.maven.plugins:uptodate-maven-plugin:0.2.0:dependency (default) on project example: There is a more up-to-date version ( 2.6 ) of the dependency commons-io:commons-io:2.0 available. -> [Help 1]
Here we have a build error generated by the plugin. The error message states that we are using version 2.0 when version 2.6 is available. Basically, Maven is a very useful tool. Perhaps it will seem difficult to use at first, but practice! Create your projects using Maven, and after a while you will be very pleased with the end result. This article deliberately omitted a lot of details about Maven — we focused on the most essential. But there is no limit to improvement: you can read more about Maven on its official website. Part 5. Servlets and the Java Servlet API. Writing a simple web application Part 6. Servlet containers Part 7. Introducing the MVC (Model-View-Controller) pattern
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION