One 、 What is? Maven?

Maven It is a project management tool , Its essence is a project object model (POM), It's reflected in the configuration pom.xml file , And this pom The document is Maven At the heart of , It manages the entire project lifecycle . It does two main things :

  • The project build : Compile the project 、 pack 、 test 、 Deployment and upload to private server warehouse, etc

  • Dependency management :Maven When it was born, it put forward the concept of a warehouse , The third party used in the project jar package , We are pom.xml You can configure dependency in ,Maven Will automatically go to its official central warehouse to download this jar Package to our local warehouse .

  • Central warehouse address :https://mvnrepository.com/

Two 、 Why use Maven?

  • Convenient dependency management :Java Up to now , The ecology is perfect . What functions do we use in the project , A search on the Internet must have a corresponding jar package , All kinds of functions lead to all kinds of jar Package Introduction , these jar There may be dependencies between packages , There may be version conflicts . and Maven The birth of solved these problems .

  • Build a multi module project : Now many projects are divided into multiple modules , To facilitate the development 、 It's also easy to expand . Multi module means that there will be various dependencies between modules , We run a module , Maybe this module depends on other modules . and Maven The one click build project helps us solve this problem .

  • Easy to transplant : Not before maven Era , Team collaboration to upload 、 Download a lot of jar Package import project , Time consuming 、 Laborious . And with maven , We just need to synchronize pom Files can be synchronized jar package . This is a maven The third problem to be solved .

3、 ... and 、 How do you use it? Maven?

3.1 Maven Installation

Let's not talk about this , A lot of information on the Internet . such as :https://www.cnblogs.com/KyleXu/p/9972042.html

3.2 Maven Configuration of

Maven The configuration of is relatively simple , The main thing is to modify conf Under folder setting file . Configure the following three warehouses :

Local repository

project-dependent jar The package needs to be downloaded locally to use . The local warehouse is from maven Private server or remote warehouse download jar Storage address , The default is Current user name \.m2\repository , I suggest a good place to remember , It is convenient to check whether the package is downloaded to the local . open setting.xml Search for localRepository Change to a custom address .

<localRepository>D:\Repository</localRepository>

Location of configuration , Here's the picture :

 Local repository

Private service warehouse

The words of this warehouse , It's usually used inside the company . Used to store your own jar package . open setting.xml File search mirrors , Configure the company's image address .

<mirror>
	<id>nexus-repos</id>
	<mirrorOf>*</mirrorOf>
	<name>Team Nexus Repository</name>
	<url>http://127.0.0.1:8081/nexus/content/groups/public</url>
</mirror>

Remote warehouse

A remote warehouse is a maven Officially maintained , Contains a lot of jar The warehouse of the package . The default for this library is maven Official , But downloading is very slow . So Alibaba, the industry model, also launched a domestic mirror image , We usually configure the remote warehouse as the image address of Ali , You can download it quickly jar Bag . It's the same as the private server warehouse , The remote warehouse is also configured in <mirrors> tag .

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

Location of configuration , Here's the picture :

 Remote warehouse

Someone may have asked , Configure so many warehouses . Exactly? jar From which download ? I'm confused , Don't worry. , I spent a flowchart , Its search order is this : There's no need for a local network , Priority should be given to finding ; Can't find , Then go to the high-speed private Internet service to find ; Then it's the Internet remote warehouse with lower speed .

maven  Find file process

3.3 Maven The order of

Common commands

command meaning remarks
mvn clean eliminate Before packing , Empty the last bag
mvn compile compile take java Code compiled into class file
mvn test test Run unit tests
mvn install Install locally Install to local warehouse , It's usually jar package
mvn package pack Usually in target Generate package under Directory ,jar or war
mvn deploy Upload Upload to private service , Need to be in setting.xml File configuration private server warehouse and account password

That's all maven Common commands , It should be noted that : Rarely do we run just one of these commands , It's all combined . For example, packing to local , You have to empty the original bag before packing ? That combination is mvn clean + mvn install

Of course , stay IDEA In the development maven project , We don't need to hit . Just click on the corresponding command ( You can also press and hold ctrl Select multiple commands to run together )

maven  operation

To make a long story short , Choose the packing order according to your own needs . There are other orders :

  • maven Detailed Command Reference :https://www.jianshu.com/p/ee7bc34d7ccc

establish maven project

Now it's usually cooperation idea newly build maven Project , This order is seldom used , But we still have to know : Generate maven The principle of the project is , Rely on a plug-in maven-archetype-plugin, Then this plug-in comes with some archetype Template , It can also be said to be the skeleton of the project . among :-DgroupId and -DartifactId Fill in the project coordinates you want , commonly -DgroupId It's the flip of the company name , such as com.google and -DartifactId It's the name of the project . most important of all -DarchetypeArtifactId, He specifies the skeleton to create .

mvn archetype:generate -DgroupId=com.nasus -DartifactId=maven-test -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

 establish  maven  Project success

Click in , Only src The folder and pom.xml file :src Is the most important directory , Code and test cases and resources are all here , about maven In terms of projects ,pom.xml It's also essential .

 Project structure

use idea The open project structure is like this :

idea  open

pom.xml The content of :

<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/maven-v4_0_0.xsd">

    <!-- Declare which... The project descriptor follows  POM  Model version , above  xsd  The specification defines this version , By default , It doesn't need to be modified , Not delete -->
    <modelVersion>4.0.0</modelVersion>

    <!-- Community unique identifier -->
    <groupId>com.nasus</groupId>

    <!-- The project unique identifier locates the package -->
    <artifactId>maven-test</artifactId>

    <!-- Packaging type -->
    <packaging>jar</packaging>

    <!-- Packaged version -->
    <version>1.0-SNAPSHOT</version>

    <!-- Package name -->
    <name>maven-test</name>

    <!-- Never mind , Delete it -->
    <url>http://maven.apache.org</url>

    <!-- The project needs to rely on  jar  package -->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

For reasons of length , I won't go into details here pom.xml The label , Please see :

  • pom Label introduction reference :https://www.runoob.com/maven/maven-pom.html

Package the project to the local warehouse

Because the project is java project , Before packing , We will be having pom.xml Of the configuration item JDK Version, and maven The plug-in version , stay <dependencies> Add item attribute configuration before label , The full configuration is as follows :

    <!-- Item attribute , stay  <dependencies>  Before to add -->
    <properties>
        <!-- JDK Compiled version  -->
        <java.version>1.8</java.version>
        <!--  Project code  -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- JDK Compiled version  -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>
    <!-- The project needs to rely on  jar  package -->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Choose the command , Here I choose clean、compile、package:

 Choose the command

Click the green execute button , stay target Generate under directory maven-test-1.0.SNAPSHOT.jar:

 Packing results

Skip unit tests

In development , We often need local tests , At this time, we don't need to run unit tests . therefore , We can skip unit tests : Choose test, Click the red box button to .

 Skip unit tests

Manual play jar Package to local warehouse

Manual play jar The application scenario of the package is : Old projects of the development company , When we can't find the one we depend on jar Source code , Rely on the jar It's not uploaded to the warehouse , There is only one in the local warehouse of colleague computers jar Packet time , We can run this command directly jar Package to our local computer warehouse , Use it happily .

mvn install:install-file -Dfile=jar The path of the package  -DgroupId=gruopId The content in  -DartifactId=actifactId The content of  -Dversion=version The content of  -Dpackaging=jar

Four 、maven Dependency management

maven adopt pom.xml To manage dependencies , We use it to describe the dependency properties of the project . Think of it as maven Map of the project , It describes the jar Coordinates of the package 、 Versions and dependencies . If you're not sure you want to introduce jar How to write the coordinates of , Yes maven Central warehouse query :

  • maven The central warehouse :https://mvnrepository.com/

4.1 maven coordinate

maven The third-party dependence of <dependencies> In label definition , Under the label <dependency> The content of the package is a jar Coordinates of , as follows pom It's introduced junit and cglib Two jar . Let's talk about what each coordinate label represents .

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>3.3.0</version>
    </dependency>
</dependencies>
  • dependencies

stay dependencies In the label , Add the... Required by the project jar The corresponding maven coordinate .

  • dependency

One dependency A label represents a coordinate , That's one jar, stay pom Introduce a jar It can be written like this :

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
</dependency>
  • groupId

company 、 group 、 Unique identifier of the individual developer ,maven Constrain it to start with the reverse domain name of the organization name that created the project , For example, the domain name of the developer is nasus.com His only identifier is com.nasus.

<!-- Community unique identifier -->
<groupId>com.nasus</groupId>
  • artifactId

Project unique identifier , An organization may have multiple projects , For convenience maven introduce ,maven The Convention names the identifier... With the project name , For example, I developed maven-test project .

<!-- Project unique identifier -->
<artifactId>maven-test</artifactId>
  • version

Version of the project . A project , There may be multiple versions . If it's a project under development , We can add a... To the version number SNAPSHOT, Indicates that this is a snapshot version .

What is a snapshot ?

For version , If maven I have downloaded the specified version file before , for instance maven-test:1.0,maven There will be no new downloads available from the warehouse 1.0 file . To download the updated code ,maven-test The version of needs to be upgraded to 1.1.

Snapshot is a special version , Specifies a copy of the current development progress . Different from the regular version ,maven Each build checks for new snapshots in the remote repository . Our own modules rely on the modules developed by our colleagues , Normally , Colleagues will publish a snapshot of the updated code to the warehouse every time .

The default version number of a new project is the snapshot version , For example, it is used above maven Order the new maven-test project :

SNAPSHOT

4.2 Depend on the range

  • scope

maven Different stages of the project are introduced to classpath The dependence in is different , for example , Compile time ,maven Compile related dependencies will be introduced classpath in , When testing ,maven Test related dependencies will be introduced to classpath in , Runtime ,maven Will introduce run related dependencies classpath in , And dependency range is used to control dependency on these three classpath The relationship between .  As shown in the figure below :

 Depend on the transfer , chart : Novice tutorial

scope Indicates the scope of the dependency , It has compile( Compile phase )、test( Testing phase )、provided( Supply stage )、runtime( Operation phase )、system( System phase )、import( Import phase ) Six options . among compile By default .system and import Use less , Don't go into details .

The scope of application of different dependencies is different , Take some of the most typical chestnuts :

Range Compilation works The test works Run time effective Packing works Example
compile yes yes yes yes spring-core
test no yes no no junit
provided yes yes no no javax.servlet-api
runtime no yes yes yes JDBC drive
  • compile: Compile dependency range . If not specified , The dependency scope will be used by default . Use the... Of this dependency scope Maven rely on , To compile 、 supply 、 test 、 Run four classpath Are effective . such as spring-core

  • provided: Dependency scope... Has been provided . Use the... Of this dependency scope Maven rely on , about Compiling and testing  classpath It works , But not at run time . A typical example is servlet-api When compiling and testing a project, you need to rely on , But when running the project , As the container has been provided , There is no need to maven Introduce... Again and again :

<dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
</dependency>
  • test: Unit test dependencies , Only in effect at the time of testing , So you can set its scope by test, such , When the project is packaged and released , Unit test dependencies will not follow the release . such as :
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
  • runtime: Runtime dependency range . For testing and running classpath It works , But not when compiling the main code . A typical example is JDBC Drive implementation , The compilation of the project main code only needs JDK Provided JDBC Interface , The implementation of these interfaces is required only when testing or running a project JDBC drive . therefore , We use JDBD Driving time , It can be defined as the following example :
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
    <scope>runtime</csope>
</dependency>

4.3 Exclude dependence

as follows xml, The original definition has introduced commons-net rely on , and hermes-ftp China depends on commons-net, To avoid version conflicts , We can exclude hermes-ftp Medium commons-net rely on .

<dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.6</version>
</dependency>
<dependency>
    <groupId>com.nasus.greece.jupiter</groupId>
    <artifactId>hermes-ftp</artifactId>
    <version>1.1.0-SNAPSHOT</version>
    <!-- exclude  commons-net  rely on -->
    <exclusions>
        <exclusion>
            <artifactId>commons-net</artifactId>
            <groupId>commons-net</groupId>
        </exclusion>
   </exclusions>
</dependency>

4.4 Depend on the transfer

Let's assume that there are the following project relationships :WebMavenDemo Project dependence JavaMavenService1,JavaMavenService1 Project dependence JavaMavenService2.

 Project relationships

pom.xml After the file is configured with dependencies , First of all mvn install after , Rely on the jar The bag can only be used . such as :

  • WebMavenDemo Of pom.xml The file wants to compile through ,JavaMavenService1 must mvn install
  • JavaMavenService Of pom.xml The file wants to compile through ,JavaMavenService2 must mvn install

Transitivity :

 Transitivity

Let's say we are now JavaMavenService2 increase spring-core , Then you will find out WebMavenDemo and JavaMavenService1 It will also automatically add this jar package , This is the transitivity of dependency .

Be careful : Not compile The dependency of scope is not transitive .

  • source :cnblogs.com/hzg110/p/6936101.html

4.5 Unified management of dependent versions

Introduce... Above pom When you file , We talked about properties label , It also has the function of limiting dependence jar Package version , It is often used to specify the version number... In the parent project , Then the use of this package by subprojects avoids the dependency conflicts caused by version inconsistency , It's written like this :

 Unified management version

5、 ... and 、build To configure

maven hit war Packet time , You may need some additional configuration , Please refer to the following xml file :

<build>
  <!--  Project name  -->
  <finalName>maven-test</finalName>
  <!--  Describe the location of resources in the project  -->
  <resources>
    <!--  Custom resources 1 -->
    <resource>
      <!--  Resource directory  -->
      <directory>src/main/java</directory>
      <!--  Which files are involved in packaging  -->
      <includes>
        <include>**/*.xml</include>
      </includes>
      <!--  Exclude which files do not participate in packaging  -->
      <excludes>
        <exclude>**/*.txt</exclude>
          <exclude>**/*.doc</exclude>
      </excludes>
    </resource>
  </resources>
  <!--  Set up plug-ins at build time  -->
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>2.1</version>
      <configuration>
        <!--  Compiled version of source code  -->
        <source>1.8</source>
        <!--  The compiled version of the target platform  -->
        <target>1.8</target>
      </configuration>
    </plugin>
    <!--  Resource plug-ins ( Plugins for resources ) -->  
    <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-resources-plugin</artifactId>  
      <version>2.1</version>  
      <executions>  
        <execution>  
          <phase>compile</phase>  
        </execution>  
      </executions>  
      <configuration>  
        <encoding>UTF-8</encoding>  
      </configuration> 
    </plugin>
    <!-- war plug-in unit ( Type the project into war package ) -->  
    <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-war-plugin</artifactId>  
      <version>2.1</version>  
      <configuration>
        <!-- war The name of the bag  -->  
        <warName>maven-test</warName>
      </configuration>  
    </plugin>  
  </plugins>
</build>

6、 ... and 、 Use idea build maven Polymerization Engineering

There are a lot of materials on the Internet , No more . Leave a link .

  • idea build maven Reference for polymerization Engineering :https://www.cnblogs.com/limn/p/9363416.html