Maven Foundation (1) | use Maven’s correct posture

Time:2020-2-18

1、 What is Maven?

MavenIs a project management tool, its essence is aProject object model (POM), which is common in configurationpom.xmlFile, and thispomThe document isMavenIt manages the entire project life cycle. It does two main things:

  • Project construction: compile, package, test, deploy and upload the project to private server warehouse, etc
  • Dependency management:MavenWhen it was born, it proposed the concept of a warehouse, the third party used in the projectjarBag, we’re herepom.xmlJust configure the dependency in,MavenIt will automatically go to its official central warehouse to download thisjarPackage to our local warehouse.
  • Central warehouse address: https://mvnrepository.com/

2、 Why use Maven?

  • Convenient dependency management:JavaUp to now, the ecology is very perfect. What functions do we use in the project? One search on the Internet must have corresponding functionsjarPackage, all kinds of functions lead to all kinds ofjarPackage introduction, thesejarThere may be dependencies and version conflicts between packages. andMavenThe birth of solved these problems.
  • Build a multi module project: now many projects are divided into multiple modules, which is convenient for development and expansion. Multi module means that there will be various dependencies between modules. We run a certain module, which may depend on other modules. andMavenThe one click build project helps us solve this problem.
  • Convenient transplantation: not beforemavenIn this era, teamwork needs to upload and download a lotjarPackage import project is time-consuming and laborious. And there ismaven, we just need to synchronizepomFiles can be synchronizedjarBag. This ismavenThe third problem to be solved.

3、 How to use Maven?

3.1 installation of maven

Let’s not talk about this. There are many materials on the Internet. For example: https://www.cnblogs.com/kylexu/p/9972042.html

3.2 Maven configuration

MavenThe configuration of is relatively simple, mainly to modifyconfUnder foldersettingPapers. Configure the following three warehouses:

Local warehouse

Project dependentjarThe package needs to be downloaded locally to use. Local warehouse is downloaded from Maven private server or remote warehousejarThe default isCurrent user name \. M2 \ repository, I suggest to change a good place to remember. It’s convenient to check whether the package has been downloaded to the local. opensetting.xmlsearchlocalRepositoryChange to a custom address.

<localRepository>D:\Repository</localRepository>

The configuration location is as follows:

Maven Foundation (1) | use Maven's correct posture

Private clothes warehouse

This warehouse is generally used within the company. Used to store your ownjarBag. opensetting.xmlFile searchmirrors, 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 amavenOfficially maintained, containing a large number ofjarThe warehouse of the package. This library is officially owned by Maven by default, but the download is very slow. So Alibaba, the industry model, also launched a domestic image. We usually match the remote warehouse with Alibaba’s image address, and then we can download it quicklyjarWrap it up. Like the private server warehouse, the remote warehouse is also configured in the<mirrors>Inside the label.

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

The configuration location is as follows:

Maven Foundation (1) | use Maven's correct posture

Someone may have asked, configure so many warehouses. Exactly?jarFrom which download? I’m confused. Don’t worry. I spent a flow chart. Its search order is as follows: no network is needed locally, and it’s preferred to search locally; if it’s not found, it’s found by intranet private server with higher speed; then it’s found by Internet remote warehouse with lower speed.

Maven Foundation (1) | use Maven's correct posture

3.3 Maven’s orders

Frequently used commands

command Meaning Remarks
mvn clean Eliminate Empty the last bag before packing
mvn compile Compile Compile java code into class file
mvn test test Running unit tests
mvn install Install locally Install to local warehouse, usually jar package
mvn package Pack Generally, the package, jar or war will be generated in the target directory
mvn deploy upload Upload to private server, you need to configure private server warehouse and account password in setting.xml file

The above ismavenFor common commands, it should be noted that in rare cases, we only run one of them, which are all combined. For example, when packing locally, you have to empty the original bag before packing? So the combination ismvn clean + mvn install

Of course.IDEAChina DevelopmentmavenProject, we don’t need to fight by hand. Just click on the corresponding command (or press and holdctrlSelect multiple commands to run together)

Maven Foundation (1) | use Maven's correct posture

All in all, choose the packaging command according to your own needs. For other commands, see:

  • Maven detailed Command Reference: https://www.jianshu.com/p/ee7bc34d7ccc

Create Maven project

Now, it’s usually cooperationideaA new Maven project has been created. This command is rarely used, but we still need to know: generatemavenThe principle of the project is to rely on a plug-inmaven-archetype-plugin, and then this plug-in comes with somearchetypeThe template can also be said to be the skeleton of the project. Among them:-DgroupIdand-DartifactIdFill in the project coordinates you want, general-DgroupIdIt’s the reversal of company name, such ascom.googleand-DartifactIdIt’s the name of the project. most important of all-DarchetypeArtifactId, which specifies the skeleton to create.

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

Maven Foundation (1) | use Maven's correct posture

Click in, onlysrcFolder andpom.xmlDocument:srcIt is the most important directory, where code and test cases and resources are put. For Maven project,pom.xmlIt is also essential.

Maven Foundation (1) | use Maven's correct posture

useideaThe open project structure is as follows:

Maven Foundation (1) | use Maven's correct posture

pom.xmlContents:

<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 POM Model version the project descriptor follows. The above XSD specification defines this version. It is OK by default. It does not need to be modified or deleted -- >
    <modelVersion>4.0.0</modelVersion>

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

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

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

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

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

    <! -- don't worry, just delete -- >
    <url>http://maven.apache.org</url>

    <! -- jar package the project depends on -- >
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Because of the length, we will not go into details herepom.xmlPlease refer to:

  • Reference for POM tag introduction: https://www.runoob.com/maven/maven-pom.html

Package project to local warehouse

Because the project isjavaProject, before packaging, we need topom.xmlOf configuration items inJDKVersion andmavenPlug in version, in<dependencies>Add before labelItem attributeThe complete configuration is as follows:

<! -- item properties, precede < dependencies > -- >
    <properties>
        <! -- JDK compiled version -- >
        <java.version>1.8</java.version>
        <! -- item 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>
    <! -- jar package the project depends on -- >
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Choose the command. Here I choose the commandclean、compile、package

Maven Foundation (1) | use Maven's correct posture

Click the green execution button, andtargetGenerated under the directorymaven-test-1.0.SNAPSHOT.jar:

Maven Foundation (1) | use Maven's correct posture

Skip unit tests

In development, we often need local tests, but at this time we do not need to run unit tests. So, we can skip unit tests: Selecttest, click the red box button.

Maven Foundation (1) | use Maven's correct posture

Manually print jar package to local warehouse

Manual beatingjarThe application scenario of the package is: old projects of the development company cannot be foundjarSource code, dependentjarIt’s not uploaded to the warehouse. There is only one in the local warehouse of colleagues’ computersjarWhen package, we can directly run this command tojarPackage to our local computer warehouse, happy to use.

MVN install: install file - dfile = path of the jar package - content in dgroupid = gruopid - content in dartifactid = actifid - content in dversion = version - dpackaging = jar

4、 Maven dependency management

Maven uses pom.xml for dependency management. We use it to describe the dependency properties of the project. It can be regarded as a map of Maven project, which describes the coordinates, versions and dependencies of jar packages. If you are not sure how to write the coordinates of the jar you want to import, you can query on the Maven central warehouse:

  • Maven central warehouse: https://mvnrepository.com/

4.1 Maven coordinates

Maven’s third-party dependence is on<dependencies>Defined in the label, the<dependency>The content of the package is ajarThe coordinates of are introduced by POM as followsjunitandcglibTwojar。 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

In the dependencies tab, add the Maven coordinates for the jars required by the project.

  • dependency

A dependency label represents a coordinate, that is, a jar. To introduce a jar into POM, you can write as follows:

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

The unique identifier of a company, community, or individual developer. Maven restricts it to start with the reverse domain name of the organization that created the project. For example, the developer’s domain name isnasus.comHis unique identifier iscom.nasus

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

Project unique identifier. An organization may have multiple projects. In order to facilitate the introduction of maven, the Maven convention names the identifier with the project name, such as the Maven test project I developed.

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

Version of the project. A project may have multiple versions. If it is a project under development, we can add a snapshot to the version number to indicate that it is a snapshot version.

What is a snapshot?

For version, ifmavenPreviously downloaded the specified version file, such asmaven-test:1.0mavenNew available will no longer be downloaded from the warehouse1.0Papers. To download the updated code,maven-testVersion of needs to be upgraded to1.1

A snapshot is a special version that specifies a copy of the current development progress. Unlike the regular version,mavenEach build checks for a new snapshot in the remote warehouse. Our own module relies on the module developed by our colleagues. Normally, our colleagues will issue 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, the new Maven test project created with the Maven command above:

Maven Foundation (1) | use Maven's correct posture

4.2 scope of dependence

  • scope

The dependencies introduced into classpath in different phases of Maven project are different. For example, when compiling, Maven will introduce the dependency related to compilation into classpath. When testing, Maven will introduce the dependency related to testing into classpath. When running, Maven will introduce the dependency related to running into classpath The dependency scope is used to control the relationships that depend on these three Classpaths. As shown in the figure below:

Maven Foundation (1) | use Maven's correct posture

Scope refers to the scope of dependency. It hasCompile, test, provided, runtime, system, importSix optional values. amongcompileIs the default.systemandimportIt’s not enough. I won’t elaborate.

For example, the most typical chestnuts are:

Range Effective compilation Effective test Valid at run time Package effective 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 driver
  • Compile: compile the dependency scope. If not specified, the dependency scope is used by default. Maven dependency using this dependency scope is effective for compiling, supplying, testing and running four kinds of Classpaths. such asspring-core
  • Provided: dependency scope provided. Maven dependencies that use this dependency scope are valid for compiling and testing classpath, but not at run time. A typical example isservlet-apiThis dependency is required when compiling and testing a project, but when running a project, it is not required because the container has been providedmavenRepeat:
<dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
</dependency>
  • Test: the unit test dependency range only takes effect when testing, so you can set its scope to test, so that when the project is packaged and published, the unit test dependency will not be published. For example:
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
</dependency>
  • Runtime: runtime dependency scope. Valid for testing and running classpath, but not when compiling main code. A typical example is the jdbc driver implementation. The compilation of the project main code only needs the JDBC interface provided by the JDK, and the specific jdbc driver of the above interface is only needed when the test is executed or the project is running. Therefore, when we use the JDBD driver, we can define it as the following example:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
    <scope>runtime</csope>
</dependency>

4.3 exclusion of dependency

The following XML has been introduced in the original definitioncommons-netDepend onhermes-ftpChina depends againcommons-net, to avoid version conflicts, we can excludehermes-ftpMediumcommons-netDependence.

<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 dependency -- >
    <exclusions>
        <exclusion>
            <artifactId>commons-net</artifactId>
            <groupId>commons-net</groupId>
        </exclusion>
   </exclusions>
</dependency>

4.4 dependent delivery

Assume the following project relationships:WebMavenDemoProject dependenceJavaMavenService1JavaMavenService1Project dependenceJavaMavenService2

Maven Foundation (1) | use Maven's correct posture

After the dependency is configured in pom.xml file, the dependent jar package can only be used after MVN install. For example:

  • WebMavenDemoOfpom.xmlThe file wants to be compiled,JavaMavenService1Mustmvn install
  • JavaMavenServiceOfpom.xmlThe file wants to be compiled,JavaMavenService2Mustmvn install

Transitivity:

Maven Foundation (1) | use Maven's correct posture

Suppose we nowJavaMavenService2increasespring-core, then we will find outWebMavenDemoandJavaMavenService1It’s going to automatically add thisjarPackage, which is the transitivity of dependency.

Note: noncompileThe dependency of the scope is not transitive.

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

4.5 unified management dependent version

In introducing POM files above, we talked aboutpropertiesTag is also used to limit the version of dependent jar package. It is often used to specify the version number in the parent project. Then, when the child project uses the package, it avoids the dependency conflict caused by version inconsistency. Its writing method is as follows:

Maven Foundation (1) | use Maven's correct posture

5、 Build configuration

When Maven hits the war package, it may need some additional configuration. Please refer to the following XML file:

<build>
  <! -- name of project -- >
  <finalName>maven-test</finalName>
  <! -- describe the location of resources in the project -- >
  <resources>
    <! -- custom resource 1 -- >
    <resource>
      <! -- resource directory -- >
      <directory>src/main/java</directory>
      <! -- including which files participate 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 plug-ins at build time -- >
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>2.1</version>
      <configuration>
        <! -- source compiled version -- >
        <source>1.8</source>
        <! -- target platform compiled version -- >
        <target>1.8</target>
      </configuration>
    </plugin>
    <! -- resource plug-in (plug-in of resource) -- >  
    <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 (package project as war) -- >  
    <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-war-plugin</artifactId>  
      <version>2.1</version>  
      <configuration>
        <! -- war package name -- >  
        <warName>maven-test</warName>
      </configuration>  
    </plugin>  
  </plugins>
</build>

6、 Building Maven aggregation project with idea

There are a lot of materials on the Internet. I won’t talk about them. Leave a link.

  • Reference for building Maven aggregation project in idea: https://www.cnblogs.com/limn/p/9363416.html

Last

If you see this article and like it, please forward it and like it. Wechat searchA good loserWelcome to pay attention.

Reply “1024Send you a complete set of Java, python, C + +, go, front-end, Linux, algorithm, big data, artificial intelligence, small programs and English tutorials.

Reply “E-book“50 + java ebooks.

Maven Foundation (1) | use Maven's correct posture

Recommended Today

Laravel service container must know

The article was forwarded from the professional laravel developer community. Original link: https://learnku.com/laravel/t To learn how to build an application with laravel is not only to learn how to use different classes and components in the framework, but also to remember allartisanCommand or all helper functions (we have Google). Learning to code with laravel is […]