Learn the basics of Maven

All projects are using Maven. What is Maven, why is Maven popular, and what benefits does it bring to our project development

Why learn Maven

  1. When developing large projects, using the package structure to distinguish complex code structures is not enough, so we need to introduce the concept of Module design. Maven uses this design philosophy;
  2. Importing repeated JAR packages under each project does not meet the pursuit of “write once,only once”;
  3. Manual package guide may lead to package leakage, inconsistent versions, resulting in project execution errors;

What is Maven

The core idea of Maven —

The core idea of Maven: Convention over configuration, it is used to contract Java project architectures, and a variety of template projects are rolled out.

Benefits of using Maven

  1. Maven can automatically guide packages through the configuration of POM.xml, and it can solve costly JAR package conflicts, version conflicts, and can achieve the purpose of one configuration, multiple reuse.
  2. The function of Maven module management makes the project structure clearer and makes the project redevelopment easier by reducing the coupling degree between modules.
  3. Automatically generating a directory structure that contains tests is nice;
  4. Often our projects involve a lot of code, configuration files, packaging when they are integrated. Even web engineering requires deployment to a server. Maven builds projects, manages jars, compiles and runs test files, automates packaging, and generatesThe report. Can be called programmer’s intimate small cotton-padded jacket.
  5. For projects built using Maven, the imported JAR package is just a coordinate. Greatly reduces the size of packaged projects.

The use of Maven

Are you intrigued by Maven’s profile?

Next, we will install Maven first, because Maven contains the build function, which requires the JAVA_HOME environment variable configuration. After installing Maven, we need to consider how to obtain the JAR package, and then we need to introduce Maven repository. Also, how does Maven make the project structure refreshing and what is the life cycle? Let’s find out


Maven installation and configuration

  1. Maven is a Java language service. You need to check whether the system has configured the JAVA_HOME environment variable, which is the path of JDK and the Java runtime environment.

  2. Configure Maven environment variables

    1. First, Maven supports one-click build, so environment variables need to be configuredPATHIn addition, the Maven installation path (No Chinese, no space under the directory)MAVEN_HOMEInstructions are also essential!

    1. Verify that the configuration is successful

      Type the MVN -v command to check the maven version. If it exists, the configuration succeeds!!

Maven repositories

Maven is best known for automatic package navigation. Where does the derivative JAR package come from? The Maven repository is where the JAR packages are stored.

Classification of Maven repositories

Maven repositories are divided into local repositories, remote repositories, and central repositories.

  • Local repository: the default location is C:\Users\zyz.m2\repository(mine), or you can specify your own repository location.
  • Remote repository: Also known as private server. When jar packages or plug-ins cannot be found in the local repository, the server obtains them from the remote repository by default. The remote repository can be on the Internet or in the LAN (company).
  • Central repository: Built into Maven software is the address of a remote repository, repo1.maven.org/maven2, which is provided by Ma…

Maven repository configuration

Open the MAVE_HOME/conf directory

Configure the local repository location in settings.xml

Order of use of Maven repositories

Global setting versus user setting

Maven repository address, private server configuration information needs to be configured in setting. XML, and its configuration is divided into global setting and user setting.

  • ${user.dir} /.m2/settings.xml; ${user.dir} /.m2/settings.xml;

  • The global setting is the setting in Maven installation directory, such as D:\Maven\apache-maven-3.6.3\conf\settings.xml. The configuration includes all projects built using Maven

    Summary: Maven looks for user configuration first, and if it can’t find it, it uses global configuration.

Maven’s directory structure

  • Note: It is recommended to place all development in one folderdevelopIn the

The Maven project’s canonical directory structure is shown below

Every part of the catalogue is indispensable.

When the project is compiled, the target directory is automatically generated, where the compiled class bytecode files and configuration files are stored.

Common commands for Maven

  • MVN clean: Clears previously compiled files

  • MVN compile: Compiles the main program

  • MVN test-compile: compiles test programs

  • MVN test: Executes a test

  • MVN package: package

  • MVN install: indicates the installation

  • MVN deploy: deployment

    Only the compile and install commands — are demonstrated here

    Run the compile command. To compile Java files in the SRC directory into class files, locate the Java files in the SRC directory of the project first, and then run the MVN compile command.

Maven’s life cycle

Maven builds projects into three separate life cycles

  1. Clean Lifecycle: Do some cleaning prior to the actual build.
  2. Default Lifecycle: The core part of a build, compile, test, package, deploy, etc.
  3. Site Lifecycle: Generate project reports, sites, publish sites.

Dependency management for Maven

Maven configures and manages dependencies in pom.xml. What are the specifications for dependency configurations in Pom.xml in order to obtain jars from the repository? If not, how can versioning conflicts be resolved? Let’s answer them all


The coordinates of the Maven

In the POP.xml file, you will find the specification for the location of the jar in the repository called coordinates. The coordinates are defined under the tag and each third-party dependency is written under the tag. Let’s first look at the structure of the coordinates —

 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
 </dependency>
Copy the code
  • GroupId: the unique identifier of a company or individual, usually a domain name written backwards;

  • ArtifactId: unique identifier of the project, that is, the project name

  • Version: indicates the version of a project. Generally, the SVN version control tool is used to manage the version. Therefore, a project can have multiple versions, and the versions are identified as RELEASE and SNAPSHOT

    • RELEASE: indicates an official RELEASE version
    • A SNAPSHOT version specifies a copy of a development progress. Maven checks for a new SNAPSHOT version in the repository each time a build is created.
  • Scope: Each JAR package is applied for a different period of time at compile time, because scope is required to specify the dependency scope. Scope has four commonly used values: compile, test, provide, and Runtime

    Depend on the range Compile the effective The test effectively Run effectively Packaging effectively The sample
    compile(The default) Square root Square root Square root Square root spring-core
    test x Square root x x junit
    provided Square root Square root Square root x javax.servlet-api
    runtime x Square root Square root Square root JDBC driver

Rely on the conflict

How does conflict arise in the first place?

When we first introduce the coordinates of Spring-MVC, we find that the coordinates of Spring-Beans on which Spring-MVC depends are also introduced, which is called dependency passing. This admittedly reduces the complexity of our package guide one by one, but also due to version conflicts lead to coordinate unavailable.

There are three mediation principles for resolving dependency conflicts

  1. The first declarator takes precedence: If the dependencies of two packages include another package, but the version required is different, the imported version takes precedence.
  2. That is, if you import a package first and then import other packages that depend on this package, the package in the first order will prevail.
  3. Locked version: In POM.xml, there is a Properties tag that locks the version. It can be used as follows
<properties>
        <spring.version>5.02..RELEASE</spring.version>
        <slf4j.version>1.66.</slf4j.version>
        <log4j.version>1.212.</log4j.version>
        <oracle.version>12.1. 01.</oracle.version>
        <mybatis.version>3.4. 5</mybatis.version>
        <spring.security.version>5.01..RELEASE</spring.security.version>
</properties>
Copy the code

In the IDEA environment, the SSM project is constructed using Maven

Maven’s automated package guide and one-click build features are a great advantage when developing more complex projects

First, review the basic principles of development projects

  1. Start with the dependent, easy parts;
  2. Building a good frame is the most important! The framework should include development-related configuration files, hierarchical structures, and so on.

Next we summarize the development process

  1. Create a new project using the WebApp skeleton;
  2. Write dependencies in pom.xm files, applicationContext files, spring-mVC. XML, log.properties files, and import db.properties files.
  3. Create a new table in the database, create POJO entity class, write XML mapping file, DAO layer, Service layer, Controller layer, Web layer;

2. Fill in the items

Write the pom.xml file first, except this part of the difference, the rest can be reused

<groupId>com.zyz</groupId>
  <artifactId>mavenTest02</artifactId>
  <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <! <properties> <spring.version>5.02..RELEASE</spring.version>
    <slf4j.version>1.66.</slf4j.version>
    <log4j.version>1.212.</log4j.version>
    <shiro.version>1.23.</shiro.version>
    <oracle.version>12.1. 01.</oracle.version>
    <mybatis.version>3.4. 5</mybatis.version>
    <spring.security.version>5.01..RELEASE</spring.security.version>
  </properties>
Copy the code

Store the configuration files in the newly created Resources directory

At this point, the skeleton of the project has been laid, which is the most basic, but also the most important step. The following specific preparation of the content according to the demand and easy, here will not repeat.

Do we have the full picture of Maven at this point? Of course not. Maven’s more advanced features — inheritance and aggregation — are also worth talking about.

Maven inheritance and aggregation

In development, if several interdependent classes have duplicate code, we extract it into the parent class, and in modules, we use the same idea to extract it into the parent project. At the same time, for the secondary development of code, module design also emerged. Let’s start by looking at a common development structure

Understand inheritance and aggregation

  1. What is inheritance?

Inheritance is designed to eliminate duplication. If the DAO, Service, and Web are separated to create separate projects, the contents of the POM.xml file for each project will be repeated. For example, setting the compiled version, locking the Spring version, etc., can eliminate these repeated configurations and define them in the parent project’s pon.xml.

  1. What is aggregation?

Project development is usually divided into modules. After the development of each module, the whole project needs to be run together, such as DAO, Service and Web, and finally an independent WAR operation.

supplement

Virtual path mapping

Process: Configure Maven in IDEA, configure the Tomcat server, select a customized virtual path in context, and finally deploy the project.

Possible problems

The serial number Possible problems The solution
1 Maven3.6.2 Display packet guide error Version of the degradation
2 Maven is reconfigured for each project Configure Maven global Settings
3 Tomcat in the Maven project is not accessible Configuration, server - > deployment
4 Resource export failure Configure resource in Builder

The finale


Floating in heaven and earth, a grain in the sea.