Maven introduction - download - install - use - basic knowledge

Maven introduction - download - install - use - basic knowledge

Maven's advanced usage can be viewed in this article:

Advanced usage of Maven sub-module-inheritance-aggregation-private server

01. Maven

1.1 Getting to know Maven for the first time

1.1.1 What is Maven

Maven is an open source project under Apache and a tool for managing and building java projects.

Official website: https://maven.apache.org/

The Apache Software Foundation, established in July 1999, is currently the largest and most popular open source software foundation in the world, and it is also a non-profit organization dedicated to supporting open source projects.

Open source projects: https://www.apache.org/index.html#projects-list

1.1.2 The role of Maven

What can you do with Maven?

  1. dependency management
  2. Unified project structure
  3. project build

Dependency management :

  • Convenient and quick management of resources (jar packages) that the project depends on, avoiding version conflictsinsert image description here

When using maven for project dependency (jar package) management, it is very convenient to solve this problem. We only need to add a configuration as shown in the figure below in the pom.xml file of the maven project.

insert image description here

**Unified project structure: **

  • Provides a standard, unified project structure

In project development, when you use different development tools (such as: Eclipse, Idea) to create a project project:

insert image description here

If we create a maven project, it can help us automatically generate a unified and standard project directory structure:

insert image description here

The specific unified structure is as follows:

insert image description here

Directory description:

  • src/main/java: java source code directory
  • src/main/resources: configuration file information
  • src/test/java: test code
  • src/test/resources: test configuration file information

Project build:

  • Maven provides a standard, cross-platform (Linux, Windows, MacOS) automated project construction methodinsert image description here

As shown in the figure above, we have developed a system. The code needs to be compiled, tested, packaged, and released. If these operations need to be repeated, it will be particularly troublesome. Maven provides a set of simple commands to complete the project construction.

insert image description here

To sum up, one conclusion can be drawn: Maven is a tool for managing and building java projects

02. Overview of Maven

2.1 Introduction to Maven

Apache Maven is a project management and construction tool, which is based on the concept of the Project Object Model (Project Object Model, referred to as: POM), and manages the construction, reporting and documentation of the project through a small piece of description information.

Official website: https://maven.apache.org/

The role of Maven:

  1. Convenient dependency management
  2. Unified project structure
  3. Standard project build process

2.2 Maven model

  • Project Object Model
  • Dependency Management Model (Dependency)
  • Build lifecycle & phases

1). Build lifecycle/phases (Build lifecycle & phases)

insert image description here

The part framed in purple in the above figure is used to complete the standardized construction process. When we need to compile, Maven provides a compilation plugin for us to use; when we need to package, Maven provides a packaging plugin for us to use, etc.

2). Project Object Model

insert image description here

The part framed in purple in the above figure belongs to the project object model, which is to abstract our own project into an object model with its own exclusive coordinates. As shown in the following figure, it is a Maven project:
insert image description here

The coordinates are the unique identifier of the resource (jar package), through which the location of the required resource (jar package) can be located

insert image description here

3). Dependency management model (Dependency)insert image description here

The part framed in purple in the above figure belongs to the dependency management model, which uses coordinates to describe which third-party jar packages the current project depends on

insert image description here

When we needed a jar package in our project before, we directly copied the jar package to the lib directory under the project, but now how can we find the desired jar package file with the coordinates written in the pom.xml file?

Answer: Maven repository

2.3 Maven repository

Warehouse: used to store resources and manage various jar packages

The essence of a warehouse is a directory (folder), which is used to store all dependencies (that is, jar packages) and plug-ins in development

The Maven warehouse is divided into:

  • Local warehouse: a directory on your own computer (used to store jar packages)
  • Central warehouse: the only one in the world maintained by the Maven team. Warehouse address: https://repo1.maven.org/maven2/
  • Remote warehouse (private server): generally a private warehouse built by a company team

insert image description here

When the coordinates are used in the project to import the corresponding dependent jar package, it will first check whether there is a corresponding jar package in the local warehouse

  • If there is, it is directly referenced in the project

  • If not, go to the central warehouse to download the corresponding jar package to the local warehouse

If you can also build a remote warehouse (private server), the search order of the jar package in the future will become: local warehouse --> remote warehouse --> central warehouse

2.4 Maven installation

Maven download installation and its configuration

03. IDEA integrates Maven

If we want to use Maven in IDEA for project construction, we need to integrate Maven in IDEA

3.1 Configure the Maven environment

3.1.1 Current project settings

1、选择 IDEA中 File => Settings => Build,Execution,Deployment => Build Tools => Maven

Maven download installation and its configuration

3. The compiled version of the configuration project is 11

  • The compiled version used by Maven by default is 5 (the version is too low)

insert image description here

The maven environment configured above is only for the current project. If we create another project, it will restore to the default configuration. To solve this problem, we need to configure the global maven environment.

3.1.2 Global Settings

Go to this page to complete the same operation [click the file, close the project to this page]
insert image description here

3.2 Maven project

3.2.1 Create a Maven project

1. Create an empty project

insert image description here

2. Create a module, select Maven, and click Next

insert image description here
insert image description here

insert image description here

3. Fill in the module name, coordinate information, click finish, the creation is complete
insert image description here

4. Under the Maven project, create a HelloWorld class

insert image description here

  • The directory structure of the Maven project:

    maven-project01
    |— src (source code directory and test code directory)
    |— main (source code directory)
    |— java (source code java file directory)
    |— resources (source code configuration file directory)
    |— test (test code directory )
    |— java (test code java directory)
    |— resources (test code configuration file directory)
    |— target (compile and package generated file storage directory)

5. Write HelloWorld and run it

public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("Hello Maven ...");
    }
}

3.2.2 Detailed explanation of POM configuration

POM (Project Object Model): refers to the project object model, used to describe the current maven project.

  • Use the pom.xml file to achieve

pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <!-- POM模型版本 -->
    <modelVersion>4.0.0</modelVersion>

    <!-- 当前项目坐标 -->
    <groupId>com.itheima</groupId>
    <artifactId>maven_project1</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <!-- 打包方式 -->
    <packaging>jar</packaging>
 
</project>

Detailed pom file:

  • project: the root label of the pom file, indicating the current maven project
  • modelVersion : Declares which POM model version the project description follows
    • While the version of the model itself rarely changes, it's still essential. The current POM model version is 4.0.0
  • Coordinates: groupId, artifactId, version
    • Locate the position of the item in the local warehouse, and a coordinate is composed of the above three tags
  • packaging : The packaging method of the maven project, usually set to jar or war (default: jar)

3.2.3 Detailed explanation of Maven coordinates

What are coordinates?

  • The coordinates in Maven areA unique identifier for the resource, the resource location can be uniquely located by this coordinate
  • Use coordinates to define the project or introduce dependencies needed in the project

The main components of Maven coordinates

  • groupId: Define the name of the organization to which the current Maven project belongs (usually the domain name is reversed, for example: com.itheima)
  • artifactId: defines the current Maven project name (usually the module name, such as order-service, goods-service)
  • version: defines the current project version number

The following figure is to use coordinates to represent an item:

insert image description here

Notice:

  • The resources mentioned above can be plug-ins, dependencies, and the current project.
  • If our project is dependent on other projects, it also needs coordinates to import.

3.3 Import Maven project

  • Method 1: Use the Maven panel to quickly import projects

Open IDEA, select the Maven panel on the right, click the + sign, select the pom.xml file of the corresponding project, and double-click it

insert image description here

Note: If there is no Maven panel, select View => Appearance => Tool Window Bars

  • Method 2: Use idea to import module project

File => Project Structure => Modules => + => Import Module

insert image description here

Find the pom.xml to import the project

insert image description here

04. Dependency management

4.1 Dependency configuration

Dependency: Refers to the jar packages required for the current project to run. Multiple dependencies can be introduced into a project:

For example: In the current project, we need to use logback to record logs. At this time, we can introduce the dependency of logback in the pom.xml file of the maven project. Specific steps are as follows:

  1. Write the dependencies tag in pom.xml

  2. Use dependency to introduce coordinates in the dependencies tag

  3. Define the groupId, artifactId, version of the coordinates

<dependencies>
    <!-- 第1个依赖 : logback -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.11</version>
    </dependency>
    <!-- 第2个依赖 : junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
  1. Click the refresh button to import the newly added coordinates
    • Refresh dependencies: ensure that the latest coordinates can be added every time a new dependency is introduced or an existing dependency configuration is modified

insert image description here

Precautions:

  1. If the imported dependency does not exist in the local warehouse, it will connect to the remote warehouse/central warehouse, and then download the dependencies (this process will be time-consuming, please wait patiently)
  2. If you do not know the dependent coordinate information, you can search in mvn's central warehouse (https://mvnrepository.com/)

Several ways to add dependencies:

  1. Leverage dependent coordinates for central repository search

insert image description here

  1. Use the IDEA tool to search for dependencies
    [thief slow –]
    insert image description here

  2. After getting used to maven proficiently, quickly import dependencies

insert image description here

4.2 Dependency delivery

4.2.1 Dependency is transitive

When we didn't use maven in the early days, adding dependent jar packages to the project required copying all the jar packages to the project project. As shown in the figure below, when logback-classic is required, since logback-classic depends on logback-core and slf4j, all three jar packages must be copied to the project project

insert image description here

We are using maven now. When you need to use logback-classic in the project, you only need to add the dependency coordinates of logback-classic in the pom.xml configuration file.

insert image description here

Only the logback-classic dependency is added in the pom.xml file, but because maven's dependency is transitive, it will automatically import other dependent jar packages.

Dependency transfer can be divided into:

  1. Direct dependencies: dependencies established through dependency configuration in the current project

  2. Indirect dependency: If the dependent resource depends on other resources, the current project indirectly depends on other resources

insert image description here

For example in the picture above:

  • projectA depends on projectB. For projectA, projectB is a direct dependency.
  • And projectB depends on projectC and other jar packages. Then at this time, the dependencies of projectC will also be passed down in projectA. For projectA, projectC is an indirect dependency.

insert image description here

4.2.2 Excluding dependencies

Question: Earlier we said that dependencies are transitive. Then A depends on B, and B depends on C. If A does not want to depend on C, can it be done?

Answer: In a maven project, we can do this by excluding dependencies.

What is an exclusion dependency?

  • Exclude dependencies: Refers to actively disconnecting dependent resources. (Excluded resources do not need to specify a version)
<dependency>
    <groupId>com.itheima</groupId>
    <artifactId>maven-projectB</artifactId>
    <version>1.0-SNAPSHOT</version>
   
    <!--排除依赖, 主动断开依赖的资源-->
    <exclusions>
    	<exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Dependency exclusion example:

  • maven-projectA depends on maven-projectB, and maven-projectB depends on Junit. Based on the transitivity of dependencies, maven-projectA also depends on Junitinsert image description here

  • After using exclude dependencies

insert image description here

4.3 Dependency scope

After importing the dependent jar package in the project, it can be used anywhere by default.

insert image description here

If you want to limit the scope of use of dependencies, you can set its scope through the scope tag.

insert image description here

Scope of action:

  1. The scope of the main program is valid (in the scope of the main folder)

  2. The test program scope is valid (within the scope of the test folder)

  3. Whether to participate in packaging and running (within the scope of package directive)

insert image description here

As shown in the figure above, specify the scope of the dependency for the junit dependency through the scope tag. Then this dependency can only be used in the test environment, and cannot be used in other environments.

The value range of the scope tag:

scope value main program test program package (run) example
compile (default) Y Y Y log4j
test - Y - junit
provided Y Y - servlet-api
runtime - Y Y jdbc driver

4.4 Life cycle

4.4.1 Introduction

Maven's life cycle is to abstract and unify all construction processes. Describes a project construction, which stages it goes through.

Before the emergence of Maven, the life cycle of project construction already existed, and software developers cleaned, compiled, tested and deployed projects every day. Although everyone is doing construction work non-stop, companies and companies, projects and projects often use different methods to do similar work.

Maven learns and reflects from a large number of projects and construction tools, and then summarizes a set of highly perfect and easy-to-extend project construction life cycles. This life cycle includes cleanup, initialization, compilation, testing, packaging, integration testing, verification, deployment and site generation of the project and almost all construction steps.

Maven divides the life cycle of project construction into 3 sets (independent of each other):

insert image description here

  • clean: Clean up work.

  • default: core job. Such as: compilation, testing, packaging, installation, deployment, etc.

  • site: Generate reports, publish sites, etc.

What specific stages are included in the three sets of life cycles? Let's look at the following picture:insert image description here

We have seen these three sets of life cycles, there are many, many stages in them, so many life cycle stages, in fact, we do not use many commonly used, mainly focus on the following:

• clean: remove files generated by the previous build

• compile: Compile the project source code

• test: run tests using a suitable unit testing framework (junit)

• package: package the compiled files, such as: jar, war, etc.

• install: install the project to the local repository

Maven's lifecycle is abstract, which means that the lifecycle itself doesn't do any real work. In Maven's design, the actual tasks (such as source code compilation) are done by plugins.

insert image description here

In order to make it easier for programmers to use the maven life cycle, the IDEA tool has given a quick access channel in the maven toolbar on the right

insert image description here

The order of the life cycle is: clean --> validate --> compile --> test --> package --> verify --> install --> site --> deploy

What we need to focus on is: clean --> compile --> test --> package --> install

Explanation: In the same life cycle, when we execute the later life cycle, the previous life cycle will be executed.

Thinking: When running the package life cycle, will the clean and compile life cycles run?

​ clean will not run, compile will run. Because compile and package belong to the same life cycle, but clean and package do not belong to the same life cycle.

4.4.2 Execution

In daily development, when we want to execute the specified life cycle, there are two execution methods:

  1. In the maven toolbar on the right side of the idea tool, select the corresponding life cycle, double-click to execute
  2. In the DOS command line, execute through the maven command

Method 1: Execute the life cycle in the idea

  • Select the corresponding life cycle, double-click to execute

insert image description here

compile:

insert image description here

test:

insert image description here

package:

insert image description here

install:

insert image description here

clean:

insert image description here

Method 2: Execute the life cycle on the command line

  1. Go to the DOS command line
    insert image description here

Guess you like

Origin blog.csdn.net/AN_NI_112/article/details/132129400