This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

preface

At the beginning of learning Java, I often encountered the need for some third-party Jar packages, such as MySQL driver package when LEARNING JDBC, and some other toolkits, such as Guava, Apache Common, etc. At the beginning, I searched and downloaded them from the official website or online, such as CS and N. Sometimes, due to various version problems, some Jar will be omitted, resulting in the code execution error. Then, The monk joji was confused and took a lot of detachs.

Until I learned the Maven build tool, I no longer need to download everywhere. I need Jar package to add the dependency to the POP. XML file, and then MVN install it. Then I must be very grateful to him/her/it. Of course, Maven can do more than manage Jar dependencies. It can also do a lot of project building.

So that’s why I wrote this column. I hope that people who read this column can take a little less of the detour I took, and learn a little easier.

With that said, let’s get back to the subject of the day.

Maven is a powerful build tool for Java software projects. The purpose of this installment is to give you an idea of how Maven works. Therefore, we will focus on the core concepts of Maven. Once you understand the core concepts, it’s much easier to go online and find documentation when you have a problem using them. Once you understand Maven and start using it, you’ll find out what it really is.

What are build tools?

A build tool is a tool that automates the construction of software projects. Building a software project usually involves one or more of the following steps:

  • Generating source code (for example, using automatically generated code in a project);
  • Document the source code;
  • Compile source code;
  • Package the compiled code as a JAR or ZIP file;
  • Install packaged code to a server, repository, or other location;

The advantage of automating the build process is that you can minimize the risk of human error when building software manually. In addition, automated build tools are often faster than performing the same steps manually.

Maven installation

To install Maven on your own system (computer), you need to download the installation package from the official website and install it as follows:

Download from Maven’s official website

  1. Set upJAVA_HOMEEnvironmental variables;
  2. Download and unzip Maven;
  3. Set up theMAVEN_HOMEThe environment variable is the directory where Maven is decompressed.
  4. willMAVEN_HOMEAdd to the PATH environment variable (%MAVEN_HOME%\bin on Windows, $MAVEN_HOME/bin on Linux);
  5. Open a command prompt and entermvn -versionVerify that the installation is successful.

If the command output is as follows, the installation is successful.

Note: Maven requires Java for execution, so you need to install the Java environment (and set the JAVA_HOME environment variable as described above) before installing Maven. Maven 3.0.5 requires Java version 1.5 or higher.

Maven Core Concepts

Centered in Maven is the POM file (project object model). POM files are XML that manage project resources, such as source code, test code, dependencies (external jars), and so on.

The POM contains references to all of these resources. The POM file should be in the root directory of the project to which it belongs.

The following diagram illustrates how Maven uses POM files and what POM files contain:

Pom file

When executing Maven commands, you need to provide Maven with a POM file on which to execute commands. Maven will then execute commands as configured for the resources in the POM.

Build Life Cycles, Phases and Goals

Maven’s Build process is divided into Build Life Cycles, Phases, and Goals. Build Life Cycles consist of a series of Phases, each consisting of a series of Goals.

When running Maven, a command is passed to Maven. This command is the name of Build Life Cycles, Phases, or Goals.

If a Life Cycles request is executed, all Phases in that Life Cycles are executed.

If a Phases is requested to execute, all of the predefined Phases that precede it will also be executed.

Dependencies and repositories

The first goal Maven performs is to check the dependencies required by the project.

Dependencies are external JAR packages used by the project. If the dependencies are not found in the local Maven repository, Maven downloads them from the central repository and places them in the local repository.

The local repository is simply a directory on your computer’s hard disk where you can specify a local repository location. You can also specify which remote repository to use to download dependencies.

Build plug-in Plugins

Build plug-ins are used to insert additional Goals while building Phases. If you need to perform a set of operations for your project that are not covered by standard Maven build Phases and Goals, you can add a plug-in to the POM file. Maven has some standard plugins already available, and you can implement custom plugins in Java if needed.

Profiles file

If you need to build your project differently, you need to use Profiles. For example, you might need to build your project locally for development and testing. You also need to build projects differently for production deployment. The two versions may be different, and you can add different Profiles files to POM files and choose which one to use when executing Maven.

Maven POM file

Maven’s POM file (project Object Model) is an XML file that configures the project’s resources, including the directories where the source code, test source code, and so on reside, the project’s external dependencies, and so on.

POM files configure what to build, but not how to build. How it is built depends on Maven building Phases and Goals.

However, custom actions can also be inserted into Maven build Phases if desired.

Each project has a POM file. The POM file is named pom.xml and should be located in the root directory of the project.

A project that is divided into subprojects usually has a POM file that is owned by the parent project, a structure that allows the entire project to be built in one step or any subproject to be built separately.

Here is a simple example of 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.heiz</groupId>
    <artifactId>java-web-demo</artifactId>
    <version>1.0.0</version>
</project>
Copy the code

The modelVersion element sets the version of the POM model being used. Use a version that matches the Maven version you are using. Version 4.0.0 matches Maven versions 2 and 3.

The groupId element is a unique ID for an organization or project (for example, an open source project). Most commonly, a groupId with a name similar to the root Java package name of the project will be used. For example, for my Java-Web-demo project, I could select the group ID com.heiz. If the project is an open source project with many independent contributors, it might make more sense to use a groupId associated with that project than with my company.

GroupId doesn’t have to be a Java package name. The symbol (dot symbol) is used to separate the words in the ID. Every one of the groupId. GroupId com.heiz will be replaced after the project is built with a directory separator stored in the local repository, with a folder for each word, so groupId com.heiz will be in a directory named MAVEN_REPO/com/heiz. The MAVEN_REPO portion of the directory will be replaced by the directory path of the Maven repository.

The artifactId element represents the name of the project to build. In my Java-Web-Demo project, artifactId will be Java-Web-demo. ArtifactId is used as the name of the subdirectory under the groupId directory in the Maven repository. ArtifactId is also used as part of the name of the JAR file that is generated when building the project, although the result can also be a WAR file or other format.

The version element represents the version number of the project. If the project has been released in different versions, such as an open source API, versioning the build is common. This allows users of the project to reference the specified version of the project. The version number is used as the name of the subdirectory under the artifactId directory. The version number is also used as part of the name of the JAR being built.

GroupId, artifactId, and Version above will generate a JAR file and place it in a local Maven repository in the following path (directory and filename):

Up your MAVEN_REPO/com/heiz/Java - web - demo / 1.0.0 / Java web - deom - 1.0.0. JarCopy the code

The parent POM

All Maven POM files inherit from a parent POM. If no parent POM is specified, the POM file inherits from the base POM. As shown below:

You can explicitly inherit from another POM file in a POM file. In this way, Settings can be changed through all generic POMs that inherit from poMs.

<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>
    
        <parent>
        <groupId>org.heiz.mojo</groupId>
        <artifactId>my-parent</artifactId>
        <version>2.0</version>
        <relativePath>../my-parent</relativePath>
        </parent>
    
    <artifactId>my-project</artifactId>.</project>
Copy the code

Inherited POM files can also override the parent POM configuration with the new configuration in their own files.

Effective POM

If you need to verify that a POM file is a valid POM in a project, you can use the following command to verify:

mvn help:effective-pom
Copy the code

A valid POM is printed out on the command line.

Run the Maven

After installing Maven and creating a Maven project, you can run Maven on the project by adding the POM file configuration.

Running Maven can be done by executing the MVN command from the command line. When executing the MVN command, take the names of Build Life Cycles, Phases, and Goals as parameters.

Such as:

mvn install
Copy the code

This command performs a build phase called Install, which builds the project and copies the packaged JAR files to the local Maven repository.

You can also specify multiple parameters, such as:

 mvn clean install
Copy the code

The command first performs the clean build life cycle, removes the compiled classes from the Maven output directory, and then executes the Install build phase.

Maven goals can also be executed by taking the build phase and goals as parameters. Here’s an example:

mvn dependency:copy-dependencies
Copy the code

This command implements the copy-Dependencies target for the dependency build phase.

Maven directory structure

Maven has a standard directory structure. If the project follows this directory structure, there is no need to specify the source code, test code directory in the POM file.

Here are the most important categories:

- src
  - main
    - java
    - resources
    - webapp
  - test
    - java
    - resources

- target
Copy the code

The SRC directory is the root of the source and test code.

The main directory is the root of the source code associated with the application itself (not the test code).

The test directory contains the test source code.

The Java directories under main and Test contain the Java code for the application itself (under main) and the Java code for the tests (under test).

The Resources directory contains additional resources required by the project, such as configuration files.

If it is a Web application, the WebApp directory contains the Java Web application. The WebApp directory will become the root directory for the Web application. Therefore, the WebApp directory contains the WEB-INF directory and so on.

The target directory is created by Maven. It contains all compiled classes, JAR files, and so on generated by Maven. When the cleanup build phase is performed, the target directory is cleaned.

Project depend on

Unless your project is small, you may need to introduce external frameworks packaged in their own JAR files. These JAR files are required on the classpath when compiling the project code.

Importing the correct version of the external JAR file is an important task. Each external JAR may also require additional external JAR files. Making sure to download the correct version of the JAR can be a hassle especially as the project gets bigger.

Maven’s built-in dependency management is designed to solve this problem. External dependencies and versions of project dependencies can be specified in the POM file, and Maven will download them and place them in the local Maven repository. If any of these external dependencies require additional dependencies, those other dependencies are also downloaded to the local Maven repository.

To specify project dependencies in the Dependencies element in the POM file. Here’s an example:

<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.heiz.demo</groupId>
    <artifactId>java-web-demo</artifactId>
    <version>1.0.0</version>

    <dependencies>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.7.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
    </build>

</project>
Copy the code

Notice the Dependencies element, which contains two dependency elements. Each dependency item describes an external dependency.

Each dependency is described by its groupId, artifactId, and Version.

When the POM file is executed by Maven, the two dependencies will be downloaded from the central repository and put into the local repository. If the dependency is already found in the local repository, it will not be downloaded.

Sometimes the dependencies in the central repository are not available. You can download the required JARS from the official website or elsewhere and use them in your local Maven repository.

External dependencies

External dependencies in Maven are dependencies (JAR files) that are not in a Maven repository (neither local, central, or remote). It might be locally located somewhere, such as in the WebApp’s lib directory, or somewhere else. Thus, the word “external” means external to the Maven repository system — not just external to the project. Most of the dependencies are outside of the project, but very rarely in the repository. If this is the case, you can configure external dependencies as follows:

<dependency>
    <groupId>mydependency</groupId>
    <artifactId>mydependency</artifactId>
    <scope>system</scope>
    <version>1.0</version>
    <systemPath>${basedir}\war\WEB-INF\lib\mydependency.jar</systemPath>
</dependency>
Copy the code

The scope element value is set to System. The systemePath element is set to point to the location of the JAR file containing the dependencies. ${basedir} points to the directory where the POM resides.

Snapshot dependencies

Snapshot dependencies are dependencies (JAR files) that are under development. Instead of constantly updating the version number to get the latest version, you can rely on a snapshot version of your project.

Each build is re-downloaded to the local repository even if the matching snapshot version is already there. This ensures that you always have the latest version for each build in your local repository.

Simply add -snapshot after the version number starting with POM to indicate that your project is a SNAPSHOT version.

<version>1.0 the SNAPSHOT</version>
Copy the code

When configuring a dependency, you can set the version to the snapshot version to implement dependency on the snapshot version.

<dependency>
    <groupId>com.jenkov</groupId>
    <artifactId>java-web-crawler</artifactId>
    <version>1.0 the SNAPSHOT</version>
</dependency>
Copy the code

You can configure how often to download snapshot dependencies in Maven’s settings.xml file.

Transfer rely on

If your project depends on a dependency, such as ABC, which itself depends on another dependency, such as XYZ, then your project depends on XYZ.

Eliminate dependence on

Sometimes, direct dependencies of a project may conflict with transitive dependencies of direct dependencies.

For example, you might be using a JAX-RS implementation that internally uses older versions of the Jackson package. However, your application may be using a newer version of the Jackson package. How do you know which of the two versions you will use?

One solution is to specify that jax-RS dependencies should exclude their dependencies on older versions of the Jackson package. This is also known as dependency exclusion.

<dependency>
  <groupId>example.jaxrs</groupId>
  <artifactId>JAX-RS-TOOLKIT</artifactId>
  <version>1.0</version>
  <scope>compile</scope>
  <exclusions>
    <exclusion>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
Copy the code

With this dependency exclusion declaration, excluded dependencies are ignored when Maven builds a project.

Maven repositories

A Maven repository is a directory of packaged JAR files containing special metadata.

Metadata is the POM file for each project to which a packaged JAR file belongs, including the external dependencies that each JAR has. It is this metadata that enables Maven to recursively download dependencies of dependencies until the entire dependency tree is downloaded and put into the local repository.

Maven has three types of repositories:

  • Local repository
  • The central warehouse
  • Remote warehouse

Maven searches these repositories for dependencies in the order described above. First in the local repository, then in the central repository or, if specified in the POM, in the remote repository.

Local repository

By default, Maven places the local repository in the user home directory on the local computer. However, you can change the location of the local repository in Maven’s settings.xml file.

The Maven settings. XML file is located in the conf/ directory of the Maven installation directory. Here’s how to specify a location for a local repository:

<settings>
    <localRepository>
        d:\data\java\products\maven\repository
    </localRepository>
</settings>
Copy the code

The central warehouse

The central repository is provided by the Maven community. By default, Maven looks in this central repository for any dependencies that are needed but not found in the local repository. These dependencies are then downloaded into the local repository.

Remote warehouse

Remote repositories are typically used to host projects within an organization that are shared by multiple projects. For example, a public safety project can be used across multiple internal projects. The outside world should not access this security project, so the central Maven repository should not be exposed to the public network. Remote repositories can be configured in POM files:

<repositories>
   <repository>
       <id>heiz.code</id>
       <url>http://maven.heiz.com/maven2/lib</url>
   </repository>
</repositories>
Copy the code

Build Life Cycles, Phases and goals

Build Life Cycles

Maven has three built-in build lifecyms:

  1. default
  2. clean
  3. site

Each of these build lifecycles is responsible for a different scenario of building a software project. Therefore, each build life cycle is executed independently. You can have Maven execute multiple build life cycles, but they will be executed sequentially and separately, as if two separate Maven commands were executed.

Default handles everything related to compiling and packaging projects.

Clean handles everything related to the removal of temporary files from the output directory, including generated source files, compiled classes, previous JAR files, and so on.

Site handles everything related to generating documentation for the project. In fact, site can generate a complete web site with documentation for a project.

Build Phases

You can implement an entire build lifecycle like clean or site, a build phase like Install (which is part of the Default build lifecycle), or a build goal like Dependency :copy-dependencies.

Note: You cannot execute the life cycle of default directly. You must specify the build phase or target during the life of the default.

When a build phase is executed, all build phases prior to that build phase in the standard phase sequence are executed. Therefore, executing the Install build phase actually means executing all build phases before the Install phase, and then executing the Install phase.

The life cycle of default is the most important because it is the part that builds the code. Because you cannot execute the life cycle of default directly, you need to execute the build phase or target from the life cycle of Default. The default lifecycle has an order of build phases and goals. The most common build phases are:

Build Phase describe
validate Verify that the project is correct and that all necessary information is available to ensure that dependencies are downloaded successfully.
compile Compile the source code for the project.
test Run tests against compiled source code using an appropriate unit testing framework. These tests should not be package or deploy.
package Package the compiled code into a distributable format, such as a JAR.
install Install packages into a local repository and use them as dependencies for other local projects.
deploy Copy the final package to a remote repository for sharing with other developers and projects.

One of the build phases can be performed through the MVN command. Here’s an example:

mvn package
Copy the code

This example executes the Package build phase, as well as all build phases prior to Package in Maven’s predefined build phase sequence.

Build Goals

Build goals are the best part of the Maven build process. A target may or may not be bound to one or more build phases. If the target is not bound to any build phase, it can only be executed by passing the target name to the MVN command. If a target is bound to multiple build phases, the target is executed in each build phase to which it is bound.

Maven build Profiles

Profiles enables you to build projects with different configurations. Instead of creating two separate POM files, you can just specify one profile with different build configurations and then use this Profile to build projects as needed.

Profiles is specified in the Profiles element of the POM file. Each profile is nested within the Profiles element. Here’s an example:

<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.jenkov.crawler</groupId>
  <artifactId>java-web-crawler</artifactId>
  <version>1.0.0</version>

  <profiles>
      <profile>
          <id>test</id>
          <activation>.</activation>
          <build>.</build>
          <modules>.</modules>
          <repositories>.</repositories>
          <pluginRepositories>.</pluginRepositories>
          <dependencies>.</dependencies>
          <reporting>.</reporting>
          <dependencyManagement>.</dependencyManagement>
          <distributionManagement>.</distributionManagement>
      </profile>
  </profiles>

</project>
Copy the code

The profile configures what changes should be made to the POM file at build time. The element in the profile element overrides the value of the element with the same name in the POM.

In the Profile element, you can see an Activation element. This element describes the conditions that trigger the build profile to use. One way to select profiles is to set the configuration file to use in the settings.xml file. Another option is to add -p profile-name on the Maven command line.

Plugins Plugins

The Maven plug-in allows you to add your own operations to the build process. You can create a simple Java class that extends a special Maven class and then create a POM for your project. Plug-in development will be covered in later installments of this column.

summary

Today’s content focuses on the core concepts of Maven, including POM files, build processes, phases and goals, dependencies, repositories, Profiles and plug-ins.

Hopefully, this installment will give you a better understanding of Maven, and the next installment will use a project to expand on what we learned today.

Click “follow” to receive updates of subsequent articles in time, if you feel helpful, click “like” is the biggest encouragement for me!