preface

Apache Maven, a cross-platform software project management and automated build tool, is provided by the Apache Software Foundation. Maven mainly serves java-based project construction, dependency management and project information management. The goal of Maven is to provide developers with the shortest possible time to know the full status of their project development efforts. These include:

  • Simplify the project build process
  • Provide a unified project construction system
  • throughPOM(project object model) Provide important information about a project
  • Provide guidelines for best project development practices

The following article gives you an overview of Maven’s use through installation, basic command usage, and a small practical example. In addition, the samples in this article are based on JDK1.8 and Maven3.

Environment to prepare

Before installing Maven, ensure that the JDK is installed locally and the JAVA_HOME environment variable is configured. You can verify this by running the following command on CMD:

Echo %JAVA_HOME% # Output JAVA_HOME environment variable value Java -version # Output Java version informationCopy the code

If the JDK installation path and Java version information are printed correctly, you are ready to proceed to the next step. Otherwise, you may need to download a JDK from the official website and configure the environment variables as shown below:

Install Maven

After you have installed the JDK locally and configured the environment variables, you can start installing Maven. First go to the official website and then find the installation package to download.

After the download is complete, unzip to the local folder. In my case, I unzip to disk D:

After decompressing, we will first configure an environment variable named M2_HOME, which corresponds to the location of the personal Maven folder:

Then configure %M2_HOME%\bin in the Path system variable:

After the configuration is complete and saved, re-open CMD and run the following command to verify the installation. If correct information is displayed, it indicates that the installation is successful:

Echo %M2_HOME% # Output Maven installation location MVN -v # Output Maven version informationCopy the code

Pay attention to

You may be wondering why we downloaded Maven3 and configured an environment variable named M2_HOME. This is mainly because the environment variable was configured as MAVEN_HOME on Maven1, changed to M2_HOME on Maven2, and continued to be named M2_HOME on Maven3. Since Maven3.5.0, M2_HOME has been deprecated, so we only need to configure D:\apache-maven-3.6.3\bin in the Path, but we still use M2_HOME.

Installation Directory

Before we explain the use of Maven, let’s familiarize ourselves with the contents and functions of the various folders in the Maven installation directory (based on Version 3.6.3 of Maven) :

  • bin

This folder contains the scripts that the MVN runs to configure Java commands, prepare the classpath and associated Java system properties, and then execute the Java commands. MVN is a shell script based on UNIX platform, and mvn. CMD is a running script based on Windows platform. When we type an MVN command on the command line, we are actually invoking these scripts. MvnDebug and mvnDebug.cmd are also included in this folder. This script contains all the functions of the MVN script, except for the MAVEN_DEBUG_OPTS configuration, which is used to debug Maven. This folder also contains m2.conf and mvnyjp files, of which m2.conf is the classWorlds profile and mvnyjp is intended to work with Yourkit Profiler. There is no introduction to Classworlds and Yourkit Profiler in this article, you can find your own information if you are interested.

  • boot

This folder contains only the JAR package and its associated license file for Plexus-Classworlds, a class loading framework that Maven uses to load its own libraries.

  • conf

This file contains one of the settings. XML files we’ve seen the most, which is used to configure proxies, mirrors, plug-ins, etc.

In addition, it also contains a toolchains. XML configuration file and a logging folder. Toolchains. XML is mainly to facilitate us to specify the JDK version used by the project. The Logging folder (which contains a configuration file called simplelogger.properties) is used to configure our logging while using Maven.

  • lib

This folder contains all of the libraries Maven needs at runtime, which I won’t cover here.

  • other

In addition, LICENSE, NOTICE, readme. TXT are used to describe open source agreements and brief introduction files.

We practice

In order to learn more about Maven configuration files and basic commands, we will not use THE IDE integrated with Maven such as IDEA. We will use VS CODE to explain the following examples.

First, we create a folder named maven, open it with VS CODE, create a new folder named pom.xml, and enter the following:


      
<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.butterfly.maven</groupId>
    <artifactId>demo</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <! - optional -- -- >
    <name>a demo maven project</name> 
    
</project>
Copy the code

The following is a brief introduction to the contents of the file:

The first line of the file is the XML header, just like HTML has
header is used to tell standard Common Markup Language parsers how to parse the document, in XML’s case, to specify the version and encoding of the document. Next comes Project, which declares some POM-related namespaces and XSD elements that make it easy to edit XML documents while using the IDE. There are four more sibling elements under the root element project, which are described below:

  • modelVersion: made currentPOMThe version of the model, forMaven2andMaven3For example, the value is fixed at 4.0.0.
  • groupId: defines the group to which the project belongs. Usually, the project name is written in reverse of the domain name of the company or organization. For example, the company domain name isabc.com, project namedemo, thengroupIdiscom.abc.demo.
  • artifactId: defines the currentMavenOnly one in the projectIDWhen a project contains multiple subprojects, we need to pay special attention to naming.
  • version: specifies the version of the current project,SNAPSHOTMeans snapshot, which means the current project is in an unstable version.
  • name: declares a project name that makes it easier for users to understand. Changing elements is optional.

Then we started to write the main code of the project. We first created a SRC /main/ Java directory in the Maven folder according to the Maven specification, and then created a file in that directory according to the groupId and artifactId names in the XML: Com/butterfly/maven/demo/Sum, Java, and write the following content:

package com.butterfly.maven.demo;

public class Sum {

    private static int sum(int[] arr) {
        int sum = 0;
        for (int val : arr) {
            sum += val;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(sum(new int[] {1.3.5.7.9})); }}Copy the code

Then execute the MVN clean compile command in the root directory of the project to compile, and you get the following output (which is omitted from the following output because many plug-in dependencies are downloaded the first time around) :

[INFO] Scanning for projects... [INFO] [INFO] ----------------------< com.butterfly.maven:demo >---------------------- [INFO] Building a demo maven 1.0 the SNAPSHOT project [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- (jar) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] - [INFO] Maven-clean-plugin :2.5:clean (default-clean) @demo -- [INFO] Deleting D:\Temp\ maven-target [INFO] [INFO] -- Maven-resources-plugin :2.6:resources (default-resources) @demo -- [INFO] skip non existing resourceDirectory D:\Temp\maven\ SRC \main\resources [INFO] [INFO] -- maven-compiler-plugin:3.1:compile (default-compile) @ demo -- [INFO]  Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\Temp\maven\target\classes [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] Total time: 1.975 s [INFO] Finished at: 2020-10-02T21:27:55+08:00 [INFO] ------------------------------------------------------------------------Copy the code

Maven-clean-plugin :2.5:clean: maven-clean-plugin:2.5:clean: maven-clean-plugin:2.5:clean Maven-resources-plugin :2.6:resources is not available in the project, so it is skipped. Finally, maven-compiler-plugin:3.1:compile is executed to compile the main code. And put the compiled results into the target/classes directory as shown below:

Next, we will write the test code. First, we will continue to create the test/ Java directory in the SRC/directory according to Maven specifications. Then, before writing the formal test code, we will introduce the JUnit dependency.

<! Add it to the project root element
<dependencies>
	<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
	</dependency>
</dependencies>
Copy the code

Then we can write our test code, we create demo/ sumtest. Java file in SRC /test/ Java/directory, and write the following:

package demo;

import org.junit.Test;
import static com.butterfly.maven.demo.Sum.sum;
import static org.junit.Assert.assertEquals;

public class SumTest {

    @Test
    public void testSum(a) {
        assertEquals(10, sum(new int[] {1.2.3.4})); }}Copy the code

Then we start the terminal in the root directory and run the MVN Clean test command (the first run will also download some plug-ins, the download output is also omitted here). We get the following information in the terminal:

[INFO] Scanning for projects... [INFO] [INFO] ----------------------< com.butterfly.maven:demo >---------------------- [INFO] Building a demo maven 1.0 the SNAPSHOT project [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- (jar) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] - [INFO] Maven-clean-plugin :2.5:clean (default-clean) @demo -- [INFO] Deleting D:\Temp\ maven-target [INFO] [INFO] -- Maven-resources-plugin :2.6:resources (default-resources) @demo -- [INFO] skip non existing resourceDirectory D:\Temp\maven\ SRC \main\resources [INFO] [INFO] -- maven-compiler-plugin:3.1:compile (default-compile) @ demo -- [INFO]  Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\Temp\maven\target\classes [INFO] [INFO] --- Maven-resources-plugin :2.6:testResources (default-testresources) @demo -- [INFO] skip non existing resourceDirectory D:\Temp\maven\ SRC \test\resources [INFO] [INFO] -- maven-compiler-plugin:3.1:testCompile (default-testcompile) @demo --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\Temp\maven\target\test-classes [INFO] [INFO] -- Maven-surefire-plugin :2.12.4:test (default-test) @ demo --- [INFO] Surefire report directory: D:\Temp\maven\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running demo.SumTest Tests run: 1, Failures: 0, Errors: B, Skipped: 0, elapsed: 0, Skipped: 0, elapsed: 0 SEC Results: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] Total time: 3.166 s [INFO] Finished at: 2020-10-02T22:17:30+08:00 [INFO] ------------------------------------------------------------------------Copy the code

MVN clean test: clean, resources, compile MVN clean test: clean, resources, compile TestResources, testCompile, and test, respectively. We then print the output after executing the unit tests. We can see that one test (the testSum test method set up for us) was executed, and no tests failed.

Pay attention to

For different versions of Maven, the first time you perform the above operations, you may receive an error about the JDK version, indicating that the compilation version is too low. In this case, you need to add the following configuration to pom.xml:

<! Add it to the project root element
<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.8</source>
				<target>1.8</target>
			</configuration>
		</plugin>
	</plugins>
</build>
Copy the code

In addition, because Maven installs dependencies from foreign sites by default, we need to configure the local image to speed up the download. In this case, we need to modify the settings. XML file. After opening settings.xml, look for the mirrors TAB and add the following configuration internally:

<mirror>
	<id>alimaven</id>
	<name>aliyun maven</name>
	<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
	<mirrorOf>central</mirrorOf>        
</mirror>
Copy the code

Also it is important to note that all depends on the location of the default download package is ~ / m2 / repository, here to represent user directory of the individual, for me is corresponding to the C: / Users/ZJW/m2 / repository. Therefore, if you do not want jar packages to be placed on disk C, you need to add the following configuration:

<localRepository>D:/jar</localRepository>
Copy the code

This way, all dependencies are stored in the D:/jar directory.

Package and run

In Maven, we can package the project with the MVN clean package command (the default package type is JAR). If we enter the above command in CMD, we can get the following output (omits the same output as in the above command) :

[INFO] -- maven-jar-plugin:2.4:jar (default-jar) @ demo -- [INFO] Building JAR: D: \ Temp \ maven \ target \ demo - 1.0 - the SNAPSHOT. Jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSCopy the code

After executing, we can find the jar package we generated in the target/ directory. In addition, it’s ok to import our own JAR packages into other projects if we want to refer to them just like any other jar package, but it would be cumbersome to copy the jar packages into other projects one by one every time, but with Maven, We only need the MVN clean install command to install the jar package of the current project into the local repository:

It can be found that compared with MVN Clean package, there are several more output lines as follows:

[INFO] -- Maven-install-plugin :2.4:install (default-install) @demo -- [INFO] Installing D: \ Temp \ maven \ target \ demo - 1.0 - the SNAPSHOT. Jar to D: \ jar \ com \ butterfly \ maven 1.0 SNAPSHOT \ demo \ \ demo - 1.0 - the SNAPSHOT. Jar [INFO] Installing D: \ Temp \ maven \ pom XML to D: \ jar \ com \ butterfly \ maven 1.0 SNAPSHOT \ demo \ \ demo - 1.0 - the SNAPSHOT. PomCopy the code

According to the information, we can know, we generate the jar package is stored in D: / jars/com/butterfly/maven/demo / 1.0 – the SNAPSHOT/directory, we can open the file explorer to verify:

This allows us to reference our own JAR packages in other projects with the following configuration:

<dependency>
    <groupId>com.butterfly.maven</groupId>
    <artifactId>demo</artifactId>
    <version>1.0 the SNAPSHOT</version>
</dependency>
Copy the code

So far, however, we have not run the main part of the main code. Because the default jar is missing the manifest configuration, there is no way to run the jar directly. In order to generate the jar that can be executed, we also need to add the following configuration in pom.xml:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-shade-plugin</artifactId>
	<version>1.2.1</version>
	<executions>
		<execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins. shade.resource.ManifestResourceTransformer">             					
                      <mainClass>com.butterfly.maven.demo.Sum</mainClass>
                    </transformer>
                </transformers>
            </configuration>
		</execution>
	</executions>
</plugin>
Copy the code

Run the MVN clean install command again and you can find two JAR packages in the target/ directory:

The jar starting with orgin is used for the jar that we could not execute directly before, and the other jar is directly executed, so we can test it:

And you’re done!

conclusion

This article gives you a brief introduction to Maven, including the installation of Maven and the use of some basic commands. I will continue to explain other aspects of Maven in the future, which I hope will be of some help to you.

The resources

  • Maven in Action
  • Maven.apache.org/what-is-mav…