The most powerful Maven tutorial-teach you step by step how to use Maven to quickly build projects

1. Efficiently Build Java Applications: Getting Started and Advanced with Maven

Table of contents


1. Introduction to Maven and quick start

1.1 Introduction to Maven

https://maven.apache.org/what-is-maven.html

Maven is a tool for Java project build management and dependency management (software). Maven can be used to automate building, testing, and packaging and release projects, greatly improving development efficiency and quality.

Summary: Maven is a software, master software installation, configuration, and basic functions (project construction, dependency management) Use this course The main goal!

1.2 Understanding the main functions of Maven

  1. scene concept

    Scenario 1: For example, our project requires third-party libraries (dependencies), such as Druid connection pool, MySQL database driver and Jackson, etc. Then we can write the required dependency information into the configuration file of the Maven project, and the Maven software will automatically download and copy these dependencies to the project, and will also automatically download the required dependencies! Make sure the dependency versions are correct, conflict-free and complete!

    Scenario 2: After the project development is completed, we want to turn the project into a .war file and deploy it to the server for running. Using Maven software, we can pass a one-line build command ( mvn package) rapid project building and packaging! Save a lot of time!

  2. Dependency management:

    Maven can manage project dependencies, including automatically downloading required dependent libraries, automatically downloading required dependencies and ensuring that there are no version conflicts, dependency version management, etc. Through Maven, we can easily maintain the external libraries that the project depends on, and we only need to write the configuration.

  3. Build management:

    Project construction refers to the process of converting source code, configuration files, resource files, etc. into applications or libraries that can be run or deployed!

    Maven can manage the compilation, testing, packaging, deployment and other build processes of the project. By implementing a standard build lifecycle, Maven ensures that every build process follows the same rules and best practices. At the same time, Maven's plug-in mechanism also allows developers to extend and customize the build process. Actively triggering the build requires only simple command operations.
    Insert image description here

1.3 Maven installation and configuration

https://maven.apache.org/docs/history.html

Selected version:

apache-maven-3.6.3-bin.zip

release time maven version jdk minimum version
**2019 - 11 - **25 3.6. 3 Java 7
  1. Install

    Installation conditions: Maven needs to install the java environment locally and must include the java_home environment variable!

    Software installation: Right-click to unzip (green, no installation required)

    Software structure:

Insert image description here

  1. environment variables

    Environment variables: Configure maven_home and path

    Insert image description here

    Insert image description here

  2. command test

     命令行输入:mvn -v 
    # 输出版本信息即可,如果错误,请仔细检查环境变量即可!
    

    Insert image description here

Note: If the maven version is not output, most of the reasons are that the configuration of the java_home variable is incorrect, please check carefully!

  1. Configuration file

    We need to changemaven/conf/settings.xml configuration file to modify some default configurations of maven. There are three configurations that we mainly need to modify: 1. Depend on the local cache location (local warehouse location) 2. Maven downloads the image 3. Maven selects the jdk version of the compiled project!

    1. Configure local warehouse address

      In the maven conf folder, open and edit the settings.xml file

      <!-- localRepository
       | The path to the local repository maven will use to store artifacts.
       |
       | Default: ${user.home}/.m2/repository
      <localRepository>/path/to/local/repo</localRepository>
      -->
      <!-- conf/settings.xml 55行 -->
      

    D:\repository
    ```

    1. Configure domestic Alibaba image (speed up download)
    ```xml
    <!--在mirrors节点(标签)下添加中央仓库镜像 160行附近-->
    <mirror>
        <id>alimaven</id>
      <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>
    </mirror>
    ```
    
    1. Configure jdk version project construction (take jdk17 as an example)
    ```xml
    <!--在profiles节点(标签)下添加jdk编译版本 268行附近-->
    <profile>
        <id>jdk-17</id>
        <activation>
          <activeByDefault>true</activeByDefault>
          <jdk>17</jdk>
        </activation>
        <properties>
          <maven.compiler.source>17</maven.compiler.source>
          <maven.compiler.target>17</maven.compiler.target>
          <maven.compiler.compilerVersion>17</maven.compiler.compilerVersion>
        </properties>
    </profile>
    ```
    
  2. idea configure local maven

    We need to configure the configured maven software into the idea development tool! Note: The idea tool comes with maven configuration software by default, but since the configuration has not been modified, it is recommended to replace the locally configured maven!

    1. Open the idea configuration file and build tool configuration

      Click on

      file / settings / build / build tool / maven

    2. Select the local maven software

      Insert image description here

    3. Test whether the configuration is successful

      Note: If the local warehouse address does not change, there is only one reason: the maven/conf/settings.xml configuration file is written incorrectly! Just double check!

      Insert image description here

2. Maven project creation based on IDEA

2.1 Sorting out the Maven project GAVP attributes

Compared with the previous project, the Maven project has an additional set of gavp attributes. Gav needs to be specified when we create the project. p has a default value and can be modified later through the configuration file. Since we need to fill in the attributes, let’s first understand the meaning of this set of attributes!

GAVP in Maven refers to the abbreviation of four attributes such as GroupId, ArtifactId, Version, and Packaging. The first three are necessary, while the Packaging attribute is optional. These four attributes mainly create an identification for each project in the maven warehouse, similar to a person's "last name-first name". With specific identification, it is convenient for maven software to manage projects and refer to each other!

GAV follows the following rules:

1) GroupID format: com.{Company/BU}.Business Line.[Sub-Business Line], up to 4 levels.

Description: {company/BU} For example: alibaba/taobao/tmall/aliexpress, etc. BU level one; sub-business lines are optional.

Positive examples: com.taobao.tddl or com.alibaba.sourcing.multilang com.atguigu.java

2) ArtifactID format: product line name-module name. The semantics are not repeated or omitted. First go to the warehouse center to verify.

正例:tc-client / uic-api / tair-tool / bookstore

3) Version version number format recommendation: major version number. minor version number. revision number 1.0.0

1) Major version number: When incompatible API modifications are made, or new features that change the product direction are added.

2) Minor version number: treated as a backward compatible functional addition (new classes, interfaces, etc.).

3) Revision number: Fixed bugs, enhanced functions without modifying method signatures, and maintained API compatibility.

For example: Initial → 1.0.0 Bug fix → 1.0.1 Function adjustment → 1.1.1, etc.

Packaging definition rules:

Indicates what type of file the project should be packaged into. Idea identifies the maven project type based on the packaging value!

The packaging attribute is jar (default value), which represents an ordinary Java project. After packaging, it is a file ending with .jar.

The packaging attribute is war, which represents the Java web project and is packaged into files ending in .war.

The packaging attribute is pom, which means it will not be packaged and is used as the inherited parent project.

2.2 Idea builds Maven JavaSE project

Note: The version is omitted here and a default value of <version>1.0-SNAPSHOT</version> is given directly.

You can modify it at will later in the project!

Insert image description here

2.3 Idea builds Maven JavaEE project

  1. Create manually

    1. Create a javasemaven project

    2. Manually add web project structure files

      NOTE: Structure and naming fixed

      Insert image description here

    3. Modify the pom.xml file packaging method

      Modify location: under project/pom.xml

      <groupId>com.atguigu</groupId>
      <artifactId>maven_parent</artifactId>
      <version>1.0-SNAPSHOT</version>
      <!-- 新增一列打包方式packaging -->
      <packaging>war</packaging>
      
    4. Refresh and verify

      Insert image description here
      A small blue dot appears in the project's webapp folder, indicating success! !

  2. Create by plug-in

    1. Install the plugin JBLJavaToWeb

      file / settings / plugins / marketplace

    Insert image description here

    1. Create a javasemaven project

    2. Right-click and use plug-ins to quickly complete web projects

      Insert image description here

2.4 Maven project structure description

Maven is a powerful build tool that provides a standardized project structure that can help developers more easily manage project dependencies, build, test, and release tasks. The following is the file structure of the Maven Web program and the role of each file:

|-- pom.xml                               # Maven 项目管理文件 
|-- src
    |-- main                              # 项目主要代码
    |   |-- java                          # Java 源代码目录
    |   |   `-- com/example/myapp         # 开发者代码主目录
    |   |       |-- controller            # 存放 Controller 层代码的目录
    |   |       |-- service               # 存放 Service 层代码的目录
    |   |       |-- dao                   # 存放 DAO 层代码的目录
    |   |       `-- model                 # 存放数据模型的目录
    |   |-- resources                     # 资源目录,存放配置文件、静态资源等
    |   |   |-- log4j.properties          # 日志配置文件
    |   |   |-- spring-mybatis.xml        # Spring Mybatis 配置文件
    |   |   `-- static                    # 存放静态资源的目录
    |   |       |-- css                   # 存放 CSS 文件的目录
    |   |       |-- js                    # 存放 JavaScript 文件的目录
    |   |       `-- images                # 存放图片资源的目录
    |   `-- webapp                        # 存放 WEB 相关配置和资源
    |       |-- WEB-INF                   # 存放 WEB 应用配置文件
    |       |   |-- web.xml               # Web 应用的部署描述文件
    |       |   `-- classes               # 存放编译后的 class 文件
    |       `-- index.html                # Web 应用入口页面
    `-- test                              # 项目测试代码
        |-- java                          # 单元测试目录
        `-- resources                     # 测试资源目录
  • pom.xml: Maven project management file, used to describe project dependencies, build configuration and other information.
  • src/main/java: Stores the Java source code of the project.
  • src/main/resources: Stores the resource files of the project, such as configuration files, static resources, etc.
  • src/main/webapp/WEB-INF: stores the configuration file of the web application.
  • src/main/webapp/index.html: The entry page of the web application.
  • src/test/java: stores the test code of the project.
  • src/test/resources: stores test-related resource files, such as test configuration files, etc.

3. Maven core function dependencies and build management

3.1 Dependency management and configuration

Maven dependency management is one of the most important features of Maven software. Maven's dependency management can help developers automatically solve software package dependency problems, allowing developers to easily integrate modules or third-party frameworks developed by other developers into their own applications or modules to avoid version conflicts and missing dependencies. question.

By defining the POM file, Maven can automatically parse the project's dependencies, and automatically download and manage the dependencies through the Maven warehouse, thereby avoiding This eliminates the tedious work of manually downloading and managing dependencies and possible version conflicts.

Focus: Write pom.xml file!

Maven project information property configuration and reading:

<!-- 模型版本 -->
<modelVersion>4.0.0</modelVersion>
<!-- 公司或者组织的唯一标志,并且配置时生成的路径也是由此生成, 如com.companyname.project-group,maven会将该项目打成的jar包放本地路径:/com/companyname/project-group -->
<groupId>com.companyname.project-group</groupId>
<!-- 项目的唯一ID,一个groupId下面可能多个项目,就是靠artifactId来区分的 -->
<artifactId>project</artifactId>
<!-- 版本号 -->
<version>1.0.0</version>

<!--打包方式
    默认:jar
    jar指的是普通的java项目打包方式! 项目打成jar包!
    war指的是web项目打包方式!项目打成war包!
    pom不会讲项目打包!这个项目作为父工程,被其他工程聚合或者继承!后面会讲解两个概念
-->
<packaging>jar/pom/war</packaging>

Dependency management and addition:

<!-- 
   通过编写依赖jar包的gav必要属性,引入第三方依赖!
   scope属性是可选的,可以指定依赖生效范围!
   依赖信息查询方式:
      1. maven仓库信息官网 https://mvnrepository.com/
      2. mavensearch插件搜索
 -->
<dependencies>
    <!-- 引入具体的依赖包 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
        <!--
            生效范围
            - compile :main目录 test目录  打包打包 [默认]
            - provided:main目录 test目录  Servlet
            - runtime: 打包运行           MySQL
            - test:    test目录           junit
         -->
        <scope>runtime</scope>
    </dependency>

</dependencies>

Dependency version extraction and maintenance:

<!--声明版本-->
<properties>
  <!--命名随便,内部制定版本号即可!-->
  <junit.version>4.11</junit.version>
  <!-- 也可以通过 maven规定的固定的key,配置maven的参数!如下配置编码格式!-->
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <!--引用properties声明版本 -->
    <version>${junit.version}</version>
  </dependency>
</dependencies>

3.2 Dependency transfer and conflict

Dependency transfer means that when a module or library A depends on another module or library B, and B depends on module or library C, then A will indirectly depend on C. This dependency transfer structure can form a dependency tree. When we introduce a library or framework, build tools (such as Maven, Gradle) will automatically parse and load all its direct and indirect dependencies to ensure that these dependencies are available.

The role of dependency transfer is:

  1. Reduce duplicate dependencies: When multiple projects depend on the same library, Maven can automatically download and only download the library once. This reduces your project's build time and disk space.
  2. Automatically manage dependencies: Maven can automatically manage dependencies and use dependency delivery to simplify dependency management and make project construction more reliable and consistent.
  3. Ensure dependency version correctness: There will be no version compatibility issues between dependencies passed through dependencies, and the dependency versions must be correct!

Dependency transfer demonstration:

In the project, Jackson-related dependencies need to be imported. Through previous import experience, Jackson needs to import three dependencies, namely:

Insert image description here

Check the dependency transfer feature introduced on the website: in data-bind, it depends on the other two dependencies.

Insert image description here

Best import: data-bind can be imported directly and the required dependencies are automatically transferred

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.0</version>
</dependency>

Dependency conflict demonstration:

When the same jar package appears in a direct reference or an indirect reference! At this time, the same duplicate jar package will appear in a project, which is considered a conflict! Dependency conflicts avoid duplicate dependencies and terminate dependency transfer!

Insert image description here

Maven has the ability to automatically resolve dependency conflicts and make repeated dependency selections according to its own principles. It also provides a way to manually resolve conflicts, but it is not recommended!

How to resolve dependency conflicts (how to choose duplicate dependencies):

  1. automatic selection principle
    • Short circuit priority principle (first principle)

      A—>B—>C—>D—>E—>X(version 0.0.1)

      A—>F—>X(version 0.0.2)

      Then A depends on X (version 0.0.2).

    • When the lengths of dependency paths are the same, "the first declaration takes precedence" (second principle)

      A—>E—>X(version 0.0.1)

      A—>F—>X(version 0.0.2)

      In <depencies></depencies>, the one declared first has the same path and will be chosen first!

Small thoughts:

前提:
   A 1.1 -> B 1.1 -> C 1.1 
   F 2.2 -> B 2.2 
   
pom声明:
   F 2.2
   A 1.1 
   
   B 2.2 

3.3 Dependency import failure scenarios and solutions

When using Maven to build a project, dependency download errors may occur. The main reasons are as follows:

  1. When downloading dependencies, network failure or warehouse server downtime occurs, resulting in the inability to connect to the Maven warehouse, and thus the dependencies cannot be downloaded.
  2. The version number of the dependency or the version number in the configuration file is wrong, or the dependency is not correctly defined, causing the dependency downloaded by Maven to be inconsistent with the actual required one, thus causing an error.
  3. The local Maven repository or cache is contaminated or corrupted, causing Maven to be unable to use existing dependencies correctly and unable to re-download them!

solution:

  1. Check network connectivity and Maven repository server status.

  2. Make sure that the version number of the dependency matches the corresponding version number of the project, and check that the dependency is correct in the POM file.

  3. Clear the local Maven repository cache (lastUpdated file), because as long as the lastupdated cache file exists, refreshing will not re-download it. In the local warehouse, search down the folders in sequence according to the dependent gav attributes, and finally delete the internal files, refresh and download again!

    For example: pom.xml dependency

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.8</version>
    </dependency>
    

    document:

    Insert image description here

    Script usage:

    Clean maven error cache.bat

    使用记事本打开
    set REPOSITORY_PATH=D:\repository  改成你本地仓库地址即可!
    点击运行脚本,即可自动清理本地错误缓存文件!!
    

Note: This script will automatically clean up incomplete maven dependency download packages due to network reasons or other reasons. Incomplete packages end with .lastupdated.

3.4 Extended build management and plug-in configuration

Building concepts:

Project construction refers to the process of converting source code, dependent libraries and resource files into executable or deployable applications. This process includes multiple steps such as compiling source code, linking dependent libraries, packaging and deployment.

Insert image description here

Actively trigger scenarios:

  • Recompile: Insufficient compilation, some files are not compiled!
  • Packaging: independent deployment to external server software, packaged deployment
  • Deploy local or private server warehouse: Maven project is added to local or private server warehouse for use by other projects

Command mode build:

Syntax: mvn build command build command…

Order describe
mvn clean Clean the compiled or packaged project structure and delete the target folder
mvn compile Compile the project and generate the target file
mvn test Execute test source code (test)
mvn site Generate a display page of project dependency information
mvn package Package the project and generate war/jar files
mvn install Package and upload to maven local warehouse (local deployment)
mvn deploy Only package and upload to maven private server warehouse (private server deployment)

Visually build:

Insert image description here

Build command cycle:

The build life cycle can be understood as an ordered collection of fixed build commands. The commands after the trigger cycle will automatically trigger the commands before the cycle! It’s also an idea to simplify construction!

  • Cleaning cycle: mainly cleaning the files generated by project compilation

    Contains the command: clean

  • Default cycle: defines all the steps that need to be executed when building a real component. It is the core part of the life cycle.

    Contains the command: compile - test - package - install / deploy

  • reporting cycle

    Contains the command: site

    Packaging: mvn clean package Local repository: mvn clean install

Best use case:

打包: mvn clean package
重新编译: mvn clean compile
本地部署: mvn clean install 

Cycles, commands and plugins:

Cycle→contains several commands→contains several plug-ins!

Build using cycle commands to simplify the build process!

It’s the plugins that ultimately do the building!

Plug-in configuration:

<build>
   <!-- jdk17 和 war包版本插件不匹配 -->
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.2</version>
        </plugin>
    </plugins>
</build>

4. Maven inheritance and aggregation features

4.1 Maven project inheritance relationship

  1. inheritance concept

    Maven inheritance refers to the mechanism that allows one project to inherit configuration information from another project in a Maven project. Inheritance allows us to share the same configuration information in multiple projects, simplifying project management and maintenance.

    Insert image description here

  2. Inheritance

    Function: Unify the dependency information in the project in the parent project and perform unified version management!

    Its background is:

    • A relatively large project was split into modules.
    • Under a project, many modules are created.
    • Each module needs to configure its own dependency information.
      The requirements behind it are:
    • If multiple modules use the same framework, they should be of the same version, so the framework versions used in the entire project need to be managed uniformly.
    • The jar package combination (or dependency information combination) required when using the framework requires long-term exploration and repeated debugging to finally determine a usable combination. This solution that took a lot of effort to sum up should not be re-explored in new projects.
      By maintaining a combination of dependency information for the entire project in the parent project, it not only ensures that the entire project uses standardized and accurate jar packages; it can also accumulate past experience, saving time and energy.
  3. inheritance syntax

    • Parent project
    <groupId>com.atguigu.maven</groupId>
    <artifactId>pro03-maven-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- 当前工程作为父工程,它要去管理子工程,所以打包方式必须是 pom -->
    <packaging>pom</packaging>
    
    
    • subproject
    <!-- 使用parent标签指定当前工程的父工程 -->
    <parent>
      <!-- 父工程的坐标 -->
      <groupId>com.atguigu.maven</groupId>
      <artifactId>pro03-maven-parent</artifactId>
      <version>1.0-SNAPSHOT</version>
    </parent>
    
    <!-- 子工程的坐标 -->
    <!-- 如果子工程坐标中的groupId和version与父工程一致,那么可以省略 -->
    <!-- <groupId>com.atguigu.maven</groupId> -->
    <artifactId>pro04-maven-module</artifactId>
    <!-- <version>1.0-SNAPSHOT</version> -->
    
  4. Unified management of parent project dependencies

    • Parent project declaration version
      <!-- 使用dependencyManagement标签配置对依赖的管理 -->
      <!-- 被管理的依赖并没有真正被引入到工程 -->
      <dependencyManagement>
        <dependencies>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.0.RELEASE</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.0.RELEASE</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.0.RELEASE</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.0.0.RELEASE</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.0.0.RELEASE</version>
          </dependency>
        </dependencies>
      </dependencyManagement>
      
    • Subproject reference version
      <!-- 子工程引用父工程中的依赖信息时,可以把版本号去掉。  -->
      <!-- 把版本号去掉就表示子工程中这个依赖的版本由父工程决定。 -->
      <!-- 具体来说是由父工程的dependencyManagement来决定。 -->
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-expression</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
        </dependency>
      </dependencies>
      

4.2 Maven project aggregation relationship

  1. aggregation concept

    Maven aggregation refers to the process of organizing multiple projects into a parent project, triggering the build of the parent project, and triggering the build of the sub-projects in sequence!!

  2. polymerization

    1. Unified management of sub-project construction: Through aggregation, multiple sub-projects can be organized together to facilitate management and maintenance.
    2. Optimize the build order: Through aggregation, you can control the order of multiple projects to avoid build failures caused by confusion in build dependencies.
  3. Aggregation syntax

    A list of subprojects contained within the parent project.

    <project>
      <groupId>com.example</groupId>
      <artifactId>parent-project</artifactId>
      <packaging>pom</packaging>
      <version>1.0.0</version>
      <modules>
        <module>child-project1</module>
        <module>child-project2</module>
      </modules>
    </project>
    
  4. Aggregation demo

    By triggering the parent project build command, trigger the build of all submodules! Generate a reactor!

    Insert image description here

Guess you like

Origin blog.csdn.net/Coastlise/article/details/134758646