Introduction to Maven

1.1 Why use Maven

Because the Java ecosystem is very rich, no matter what functions you want to implement, you can find the corresponding tool classes, these tool classes are in the form of JAR packages, such as Spring, SpringMVC, MyBatis, database driver, etc., are in the form of JAR packages. Jar packages are associated with each other, and before you can use a dependency, you need to determine what other dependencies that dependency depends on, so dependency management can become cumbersome when projects are large. This is the first problem Maven solves.

Maven can also handle multi-module projects. Simple projects, single module subcontracting processing, if the project is more complex, to make a multi-module project, for example, an e-commerce project has order module, membership module, commodity module, payment module… In general, multi-module projects, each module cannot run independently, the project can run only when multiple modules are combined together. At this time, with the help of Maven tools, the project can be packaged with one click.

Before Maven, we mostly used Ant’s project building tool. Ant has a feature that it has to write every time, and every time it writes the same, the configuration is bloated. So Maven came along. Is Maven the most advanced build tool? No, it’s just that Maven is used a lot in the Java world these days. Besides Maven, there is Gradle.

1.2 What is Maven

Maven is a Project management tool that contains a Project Object Model, which is reflected in the configuration as a POM.xml file. Is a set of standards, a project lifecycle, a dependency management system, plus plugins and goals defined at the project lifecycle stage.

When we use Maven, we describe our own projects in detail through a custom project object model, POM.xml.

There are two main cores in Maven:

  • Dependency management: Unified management of JARS (Maven provides a central repository for Maven, mvnrepository.com/, when we add… Will automatically go to the central repository to download related dependencies, and resolve dependency dependency issues)
  • Project construction: Compile, test, package, deploy, upload to private server, etc

2. Maven installation

  • Maven is a Java project, so you must install the JDK first.

Maven:

  • Download Maven

Download address: maven.apache.org/download.cg…

  • Unpack and configure

Configuration, only need to configure the environment variable:

First configure MAVEN_HOME:

Then configure the environment variables:

  • Inspection installation

If you are using IntelliJ IDEA, you can use the Maven plugin in IDEA instead of downloading Maven. Maven plugin is available in\ ideaiu-2019.2.4. win\plugins\ mavenins \lib\maven3

3. The Maven configurations

In fact, without special requirements, it is ready to use as soon as it is installed. In general, a little configuration is needed, such as the central warehouse. By default, Maven’s own central warehouse is used, which has low network speed. At this time, you can modify the configuration file to change the warehouse to a domestic mirror warehouse, which is mostly used by Alibaba.

3.1 Warehouse Types

Warehouse type instructions
Local repository It’s a repository on your computer, and everyone has a repository on their computer, and the default location isCurrent user name \.m2\repository
Private servers warehouse Generally speaking, it is Maven private server built by the company, which is on the LAN and has fast access. The JAR stored in this warehouse is generally the JAR developed by the company itself
The central warehouse It is maintained by the Apache team and contains most of the JARS. Oracle database drivers are not included in the early stage, and as of August 2019, Oracle drivers are included

There are now three repositories, so how do you find jar packages?

3.2 Configuring the Local Warehouse

The default location of the local repository is the current user \.m2\repository. This location can be customized, but it is not recommended for several reasons:

  1. All the native jars are in this repository, but they don’t take up much space.
  2. The default location is hidden and not easily touched

It is of course technically possible to customize the local repository location in conf/settings.xml:

3.3 Configuring remote Mirroring

Since the default central warehouse is slow to download, you can also change the remote warehouse address to alibaba’s warehouse address:

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

This configuration is added to the mirrors node in settings. XML:

4. Common Maven commands

There are some common commands in Maven. If you are using Eclipse, you need to type the commands manually. If you are using IDEA, you can simply tap the commands.

Common commands Chinese meaning instructions
mvn clean Clean up the This command can be used to clean up files that have been compiled
mvn compile compile Compile the Java code into a Class file
mvn test test Project test
mvn package packaging Type projects into JAR packages or WAR packages, depending on the user’s configuration
mvn install The installation Manually install a JAR to the local repository
mvn deploy upload Upload the JAR to a private server

The important thing to note here is that none of these commands run independently, it has a sequence. Here’s a simple example:

I want to upload the JAR to a private server, so I need to build the JAR, I need to execute the package command, to package, of course also need to test, that is to go to the MVN test command, to test, I need to compile….. Therefore, eventually all commands will be executed once. However, developers can also manually configure not to execute a command, which is called skipping. In general, it is not recommended to skip any steps other than testing.

Of course, if the developer uses IDEA, these commands do not need to be manually typed, just click:

4.1 Build projects by commands

It is possible to build a Maven project directly by command, but in real development, it is usually possible to create a Maven project directly using Eclipse or IDEA.

Create command:

mvn archetype:generate -DgroupId=org.javaboy -DartifactId=firstapp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Copy the code

The project is successfully created if the following information is displayed:

After the project is successfully created, there are two files:

For any project, these two are the core.

In POM.xml, all project configurations are defined.

4.2 Package the project

Next, we can use the MVN package command to group the project we just created into a JAR package.

Before packaging, we need to configure the JDK version at least 7, so we also need to manually modify the POM.xml file to add the following configuration:

After the package is added, run the package command. When you run all commands, locate the directory where the POM. XML file resides.

4.3 Installing the Project to the local repository

If you need to install the project into a local repository, you can directly execute the MVN install command. Note that the MVN install command contains the ABOVE MVN package procedure.

After installing into the local repository, at this point, click on your own local repository to see the relevant JAR.

5. Use Maven in IDEA

Unlike Eclipse, you can use Maven directly after IDEA is installed.

5.1 Maven-related Configurations

IDEA, Maven’s configuration in the File – > Settings – > Build, Execution, Deployment – > Build Tools – > Maven:

5.2 Creating a JavaSE project

First when creating a project, select Maven project:

If you check Create from Archetype, you can Create a new project from a project skeleton (project template), but if you are just creating a JavaSE project, you don’t need to select a project skeleton. Just Next. Then fill in the project coordinates, groupId and artifactId.

When you’re done, go to Next. In this way, we get a JavaSE project with the same structure as the project you created with the command.

5.3 Creating a JavaWeb Project

There are two ways to create a Maven Web project in IDEA:

  • Start by creating a JavaSE project, then manually transform the JavaSE project into a JavaWeb project
  • When you create a project, select the project skeleton, and the skeleton selects WebApp

Of the two methods, the first method is recommended.

5.3.1 Transformation of JavaSE project

This way, you first create a JavaSE project with the same steps as above.

After the project is created, modify pom.xml and configure the package format of the project as WAR package. This way, IDEA knows that the current project is a Web project:

Then, select the JavaSE project, right-click and select Open Module Settings, or press F4 and select Web as shown below:

Next, in the WebApp directory, add the web.xml file.

Note that it is important to modify the web.xml file location:

When the configuration is complete, click OK to exit.

Once the project is created, deployment is the next step.

To deploy, click On Edit Configurations in the upper right corner of your IDEA first:

Then, configure Tomcat:

Next select the Deployment TAB to configure the project to publish:

Finally, click the triangle symbol in the upper right corner of IDEA to start the project.

5.3.2 Direct Creation through the WebApp Skeleton

This approach is relatively simple, requires little additional configuration, and once the project is created, it is a Web project. We just need to select the WebApp skeleton when we create the project.

After selecting the skeleton, the following steps are the same as above.

After the project is successfully created, only webApp Directory is available. At this point, you can manually create the Java and resources directories. After the project is created, right-click on Mark Directory As and Mark the Java Directory As Sources root. Just mark the Resources directory as Resources root.

Click the Enable Auto Import button whenever you see it in the lower right corner of IDEA

6. Maven dependency management

Maven projects, if they need to use third-party controls, are done through dependency management. One of the things used here is the Pom.xml file, a concept called the Project Object Model (POM). In Pom.xml, we define the form of the Maven Project, so pom.xml is like a map of the Maven Project. Similar to the web.xml file used to describe the three major Web components.

What are the things that are involved in this map?

6.1 the Maven coordinates

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
</dependencies>
Copy the code
  • dependencies

In the Dependencies TAB, add the Maven coordinates for the JARS required by the project.

  • dependency

A Dependency tag represents a coordinate

  • groupId

The unique identification of a group, company, organization, etc. The convention for the community identity is that it begins with the reverse domain name (for example org.javaboy) of the organization that created the project. A Maven coordinate must contain groupId. Some typical groupId such as Apache’s groupId is org.apache.

  • artifactId

An artifactId is equivalent to a unique identifier for an item in an organization.

  • version

A version of a project. There may be multiple versions of a project. If the project is under development, we can add a SNAPSHOT to the version number to indicate that it is a SNAPSHOT version (the default version number for a new project is a SNAPSHOT version).

  • scope

Indicates the dependency scope.

We add a lot of dependencies, but the scope of use varies from dependency to dependency. The two most typical are database-driven and unit testing.

Database driver, in the process of using, we write our own code, write JDBC code, only when the project runs, need to execute the code in MySQL driver. The scope of the MySQL driver dependency can be set to Runtime after it is added to the project, which does not take effect when compiled.

Unit tests are only available at test time, so you can set its scope to test so that when the project is packaged for release, the unit test dependencies will not follow.

6.2 Dependency Conflict

  • Causes of dependency conflicts

In the figure, A. jar depends on B. Jar, and AT the same time A. Jar depends on D. Jar. At this time, the relationship between A and B and D is directly dependent, and the relationship between A and C is indirectly dependent.

6.2.1 Conflict Resolution

  1. First define, first use
  2. Path nearest rule (direct declaration use)

Using spring-context as an example, x in the following figure represents invalid dependencies (dependencies with low priority, i.e. dependencies with close paths are preferred) :

These are the default behaviors.

We can also control it manually. Manual control is mainly achieved by removing dependencies, as follows:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.9. RELEASE</version>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Copy the code

This means to exclude spring-core dependencies from the spring-context.

7. Maven private servers

Maven repository management is also called Maven Private server or proxy repository. Using Maven Private server serves two purposes:

  1. Private server is a proxy between developer and remote repository
  2. Private servers can be used to deploy the company’s own JARS

7.1 the Nexus is introduced

Nexus is a powerful Maven repository management tool that makes it easy to manage internal repositories and simplify access to external repositories. The official website is www.sonatype.com/

7.2 installation

  • download

Download address: www.sonatype.com/download-os…

  • Unpack the

Copy the downloaded compressed package to a path without Chinese and decompress it.

  • Start the

After decompressing, open CMD window (open CMD window as administrator), locate the nexus decompression directory, and run nexus.exe/run to start the service.

This is a little bit slow, about a minute or two

After the startup is successful, enter http://lcoalhost:8081 to open the management page.

After opening the admin page, click the login button in the upper right corner to log in. The default user name and password are admin and Admin123. Of course, users can also click the Settings button to manually configure other users.

Click Repositories to view the repository details:

7.2.1 Warehouse types

The name of the instructions
proxy Represents the repository as a proxy for a remote repository, most typically the Maven central repository
hosted Host repositories, where some of the jars developed by the company are stored, as well as jars not available on Maven’s central repository
group Warehouse group, which contains proxy and host repositories
virtual Virtual warehouse

7.2.2 upload jar

Upload jar, configure two places:

  • Maven conf/settings. XML file configuration:
<server>
  <id>releases</id>
  <username>admin</username>
  <password>admin123</password>
</server>
<server>
  <id>snapshots</id>
  <username>admin</username>
  <password>admin123</password>
</server>
Copy the code

In the pom.xml file of the project where you want to upload the JAR, configure the upload path:

<distributionManagement>
    <repository>
        <id>releases</id>
        <url>http://localhost:8081/repository/maven-releases/</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <url>http://localhost:8081/repository/maven-snapshots/</url>
    </snapshotRepository>
</distributionManagement>
Copy the code

Once configured, click the deploy button or run the MVN deploy command to upload the JAR to the private server.

7.2.3 Downloading the JAR from the Private server

Add dependencies directly to the project. After adding dependencies, add additional private server addresses:

<repositories>
    <repository>
        <id>local-repository</id>
        <url>http://localhost:8081/repository/maven-public/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>
Copy the code

8. Polymerization engineering

The so-called convergent engineering is actually a multi-module project. In a relatively large Internet project, the project needs to be divided into multiple modules for development, such as order module, VIP module, payment module, content management module, CMS, CRM and so on. This split is actually closer to the idea of microservices. Within a module, you can continue to split, for example into DAOs, Services, Controllers, and so on.

Some people might say, isn’t this subcontracting all right?

Small projects can certainly be subcontracted, but large projects cannot. For example, in a large e-commerce system, there is a sub-module called user management and another sub-module called order management, both of which involve users. In this case, we need to separate the user class and make it into a separate module for other modules to call.

8.1 Multi-module project Display

|--javaboy-parent
      |-- javaboy-cms
      |-- javaboy-crm
      |-- javaboy-manger
           |-- javaboy-manager-model
           |-- javaboy-manager-dao
           |-- javaboy-manager-service
           |-- javaboy-manager-web
Copy the code

In the case of Javaboy-Manger, the Javaboy-Manager does not provide functionality by itself. It only manages its own sub-modules, each of which cannot run independently and requires four sub-modules to run together. When the project is packaged, the Model, DAO, and Service are packaged into Jars, which are then automatically copied to the Web, and the Web is automatically packaged into a WAR package.

Create an aggregation project in 8.2 IDEA

1. Create an empty Maven project:

After the project is created, the SRC directory can be removed because parent is not involved in the implementation of the business, but only manages its submodules.

2. Right-click the current project and choose New->Module

In IDEA, the parent of the current Module is specified by default. The developer only needs to fill in the artifactId of the current Module:

After the javaboy-manager is created, we can look at the Pom. XML file of javaboy-parent and see that it automatically adds packing property:

Its packaging attribute value is POm, which indicates that it is an aggregation project, and it also has modules nodes, which indicate its own sub-modules. Also, note that javaboy-Manager has a parent node that describes its parent module’s attribute values:

<parent>
    <artifactId>javaboy-parent</artifactId>
    <groupId>org.javaboy</groupId>
    <version>1.0 the SNAPSHOT</version>
</parent>
Copy the code

The parent is not just a simple parent-child relationship, it is an inheritance relationship, generally we can define a dependency or plug-in version number in the parent

3. Because Javaboy-Manager is an aggregation project, the SRC directory of Javaboy-Manager can also be deleted.

4. Select Javaboy-Manager, right-click New->Module and create a New Maven Module. This step is similar to step 2 and will not be repeated. Here, after the new Javaboy-manager-Model is created, we manually set its Packaging property value to JAR.

5. Repeat Step 4 to create javaboy-manager-service and Javaboy-manager-DAO 6 respectively. Go ahead and create the Javaboy-Manager-Web module, which, unlike other modules, needs to be packaged as a WAR. See article 5 for web module creation. 7. After the Web project is created, improve the inheritance relationship between modules.

Javaboy-manager-web depends on javaboy-manager-service. Javaboy-manager-service depends on javaboy-manager-DAO javaboy-manager-model

Note that dependencies are transitive by default, that is, dependencies on javaboy-manager-Model in javaboy-manager-DAO are also accessible in javaboy-manager-service.

The dependency relationship after configuration is shown as follows:

You can then write the code in different modules and deploy the project. Deployment mode refer to [Fifth Article]

One caveat is that in multi-module projects, web project packaging needs to be aware of the following:

  1. You can’t pack them separately
  2. If you want to pack, there are two ways:
  • The first is to manually install the Model, DAO, and Service into the local repository one by one
  • Package from the aggregator, that is, from the web parent.

Follow the wechat official account “A Little Rain in Jiangnan” and reply to Maven to get an electronic version of this article, or visitmaven.javaboy.orgCheck out this ebook.