Getting started with the MAVEN project build tool

Source: Internet
Author: User
Tags assert create directory object model aliyun
Directory

Introduction of MAVEN and environment construction create MAVEN project maven common commands automatically create directory skeleton maven coordinates and warehouse coordinates warehouse information about warehouses change the location of the local warehouse Maven lifecycle and plug-in lifecycle plug-in pom.xml common elements Introduction Maven relies on dependency range dependency transitive dependency conflict aggregation and inheritance aggregation inheritance

Preface

Although I had previously had contact with MAVEN, it was not a sufficient system. Then take advantage of this time have free time, hurriedly review again, recharge. As the following records of knowledge points, can be considered as I watch IMOOC "project management tool--maven" tutorial (if you are interested, you can go to the IMOOC website to watch the video) after the learning of the collation of knowledge to facilitate sharing and review. So below, we are officially starting to learn about Maven. Introduction to MAVEN and setting up the environment

MAVEN is a Project object model (POM) that allows you to manage software project management tools for building, reporting, and documenting your project with a small section of descriptive information.
The Maven Bin directory contains a mvn run script, and the boot directory contains a framework for the ClassLoader, which Maven uses to load its own class library; The config directory contains some configuration files, and the Lib directory contains the class library that Maven uses when it is used.
In the official website to download the corresponding Maven file decompression can be. In addition, in order to run MAVEN's commands directly on the command line, we need to configure the environment variables. In the system variable, we create the environment variable "maven_home", the value of the variable is the installation directory of MAVEN, and then add ";%maven_home%\bin" at the end of the path variable. Verify that the configuration was successful: Under the command line, enter "Mvn-v" to view the currently installed version of MAVEN. Create maven Project

Before creating the MAVEN project, let's take a look at the directory structure that the MAVEN project should have, as follows:

-src
  -Main
    -Java
      -Package
  -Test
    -Java
      -Package
  -
pom.xml

For example, we create a MAVEN project called Maven01, as follows:
The first is the contents of the main directory, which creates the Helloworld.java file in the following directory.

Maven01\src\main\java\com\wm103\maven01\model
Package Com.wm103.maven01.model;

public class HelloWorld {public
    String say () {return
        "Hello world!";
    }
}

Next, create the test directory and create the Helloworldtest.java file in the following directory.

Maven01\src\test\java\com\wm103\maven01\model
Package Com.wm103.maven01.model;

Import org.junit.*;
Import org.junit.assert.*;

public class HelloWorldTest {
    @Test public
    void Testsay () {
        assert.assertequals ("Hello world!", new HelloWorld (). Say ());
    }

Finally, the Pom.xml file is created in the root directory of the project, and the contents of the file are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0"
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 ">
    <modelVersion>4.0.0</modelVersion>

    <groupId> com.wm103.maven01</groupid>
    <artifactId>maven01-model</artifactId>
    <version> 0.0.1snapshot</version>

    <dependencies>
        <dependency>
            <groupid>junit</ groupid>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </ dependency>
    </dependencies>
</project>

Based on the above steps, we have created the first MAVEN project. In this project, the GroupID value of the Pom.xml file is the package name of the project; the Artifactid value is the module name, and the project name-module name is recommended. common commands for Maven

Mvn-v View the MAVEN version
mvn compile compile mvn project
MVN test Run the scenario created in the MAVEN Project
MVN package Package The project as a jar pack
mvn clean Delete the target directory in the MAVEN project
mvn install install jar package into local warehouse

Where mvn install command, we can use this command to package the local project into a jar to install to the local warehouse. For example, we used the Helloworld.java in the Maven01 project in the new project MAVEN02:

Package com.wm103.maven02.util;

Import Com.wm103.maven01.model.HelloWorld;

public class Speak {public
    String say () {return
        new HelloWorld (). Say ();
    }

So when we compile the MAVEN02 project in MVN compile, we get the following error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (Default-compile) on project Maven02-util:compilation failure:compilation failure:
[ERROR]/g:/studyworld/program/ideaworkspace/maven/ MAVEN02/SRC/MAIN/JAVA/COM/WM103/MAVEN02/UTIL/SPEAK.JAVA:[3,25] Package Com.wm103.maven01 does not exist
[ERROR]/g:/ STUDYWORLD/PROGRAM/IDEAWORKSPACE/MAVEN/MAVEN02/SRC/MAIN/JAVA/COM/WM103/MAVEN02/UTIL/SPEAK.JAVA:[7,28] No symbols found
[ERROR]   symbol:   class HelloWorld
[ERROR]   location: Class Com.wm103.maven02.util.Speak
[ERROR]-> [Help 1]

To solve this problem, we need to use the MVN Install command for the MAVEN01 project, package it into a jar and install it into a local repository, and secondly, we need to define MAVEN01 dependencies in the MAVEN02 project as follows:

<?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/maven-v4_0_0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.wm103.m Aven02</groupid> <artifactId>maven02-util</artifactId> <version>0.0.1snapshot</
            version> <dependencies> <dependency> <groupId>junit</groupId> 
        <artifactId>junit</artifactId> <version>4.10</version> </dependency> <dependency> <groupId>com.wm103.maven01</groupId> <artifactid>mav En01-model</artifactid> <version>0.0.1SNAPSHOT</version> </dependency> ;/dependencies> </project>
automatically create a directory skeleton

Creating the directory structure of the MAVEN project manually is actually a tedious task, and to address such issues, a archetype plugin is provided in Maven to help us create the MAVEN directory skeleton. Use the following:
1. MVN archetype:generate: Follow the prompts to fill in the selection of the creation;
2. MVN archetype:generate-dgroupid= organization name, company URL Reverse write + project name-dartifactid= project name-module name-dversion= version number-dpackage= The name of the package that exists in the code: set up the subsequent parameters to be filled out in the command. Such as:

MVN archetype:generate-dgroupid=com.wm103.maven04-dartifactid=maven04-demo-dversion=0.0.1snapshot-dpackage= Com.wm103.maven04.demo
coordinates and warehouses in Maven coordinates

In Maven, any project's dependencies, Plug-ins, and project-built outputs can be called artifacts, and all artifacts can be identified by coordinates. such as: Pom.xml in the GroupID, Artifactid, version of the three can constitute a coordinate, identify a component. Warehouse Introduction to the warehouse

The artifacts are stored in the warehouse. Warehouses are divided into local warehouses and remote warehouses. If a project does not find the required artifacts in the local repository, it will be found at MAVEN's global central Warehouse, where it will be downloaded to our local warehouse for our use. If the remote central warehouse also cannot be queried, the item will be an error.
So what is the address of the global warehouse provided? We can view it in the Lib/maven-model-builder-3.5.3.jar of the MAVEN installation directory (with different versions and different file names). Contains a pom file in the Org/apache/maven/model directory of the Jar. All of our MAVEN projects will inherit from the Pom file. In this file, we can see:

  <repositories>
    <repository>
      <id>central</id>
      <name>central Repository </name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</ layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </ Repository>
  </repositories>

Where the URL tag is set to the address of the remote central warehouse, and the snapshots tag is set to False, and the widget that is blocked from downloading as a snapshot version is also indicated.
Remote central warehouses are located in foreign countries, we can use the configuration of a mirrored warehouse, to the remote warehouse access to the mirrored warehouse. This is configured in the following ways:

<!--Modify the contents of the Mirrors node in the Conf directory settings.xml file under the Maven installation directory-->
<mirrors>
  <mirror>
    <id >maven.aliyun.com</id>
    <mirrorOf>central</mirrorOf>
    <name>aliyun maven</ name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  </mirror>
</mirrors>
Change the location of the local warehouse

For Windows, the local warehouse location of the default Maven is in the currently logged-on user directory. Such as:

C:\Users\DreamBoy\.m2\repository

Changing the location of the local warehouse also requires modifications to the settings file (configured in the 55 rows of the file) as follows:

<localRepository>H:/MySoftware/maven-repo</localRepository>
maven Lifecycle and Plug-ins Life cycle

The process of building a complete project includes: cleaning, compiling, testing, packaging, integration testing, validation, deployment.
In Maven, you include 3 sets of lifecycle, clean (cleanup project), default (build project), site (build project site). And in these 3 sets of life cycle each contains a number of sequential execution stages, that is, any stage is executed, the previous phase will be executed sequentially.
Clean (cleanup project): Pre-clean work before cleaning cleans up all the files that were built on the previous build Post-clean the files after the cleanup was performed

Default (Build project-most core): Compile Test Package Install

Site (build Project site): Pre-site The site document Post-site to be completed before the project site is built site-deploy the work to be done after the project site is built the site to the server where the release is built

Using Plug-ins in the MAVEN project can be configured in the project's Pom.xml file, as an example of configuring jetty. As follows:

<?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/maven-v4_0_0.xsd "> <modelVersion>4.0.0</modelVersion> &LT;GROUPID&GT;COM.WM103.W

    Ebdemo</groupid> <artifactId>webdemo</artifactId> <version>0.0.1SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <arti factid>junit</artifactid> <version>4.10</version> </dependency> </de pendencies> <build> <finalName>WebDemo</finalName> <plugins> & Lt;plugin> <groupId>org.mortbay.jetty</groupId> <artifactid>jetty-mav En-plugin</artifactid> <version>8.1.16.v20140903</version> <!--<groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version>--&
                Gt <executions> <execution> <!--use Jetty:run to run jetty Services after a successful package
                        ; <phase>package</phase> <goals> <goal>run</g
            oal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
pom.xml Common Element Description
<?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/maven-v4_0_0.xsd > <!--specified the version of the current POM--> <modelVersion>4.0.0</modelVersion> <!--the reverse write + project--> <groupId>com.wm103.maven01</groupId> <!--project name + module name--> <arti
    Factid>maven01-model</artifactid> <!--version number, such as 0.0.1SNAPSHOT the first 0 represents the large version number the second 0 represents the branch version number the third 0 represents the minor version number Snapshot represents snapshots, in addition to: Alpha internal testing, beta test, release stability, GA officially released--> <version>0.0.1snapshot</version 
    > <!--packaging, the default is the jar, in addition you can set package for war, zip, pom, etc.--> <packaging></packaging> <!--project Description--> <name></name> <!--project Address--> <url></url> <!--project description--> <descrip tion></description> <!--developer List-->
    <developers></developers> <!--license information--> <licenses></licenses> <!--organization Information --> <organization></organization> <!--dependencies list--> <dependencies> <!--dependencies Items, by specifying the required coordinates to identify the dependencies--> <dependency> <groupId>junit</groupId> &LT;ARTIFAC
            Tid>junit</artifactid> <version>4.10</version> <type></type> <!--dependency range--> <scope>test</scope> <!--setting depends on whether it is optional, default is False.
            If False, the subproject is inherited by default, otherwise the subproject must be shown to introduce the dependency--> <optional></optional> <!--exclude dependent delivery list-->
        <exclusions> <exclusion></exclusion> </exclusions> </dependency> </dependencies> <!--dependent Management, the role is mainly defined in the parent module,--> <dependencymanagement for child module inheritance
  > <dependencies>          <dependency> </dependency> </dependencies> </dependencymanagement&

    Gt <!--provide appropriate support for the construction of the MAVEN project--> <build> <!--plugin list--> <plugins> <
                Plugin> <groupId></groupId> <artifactId></artifactId> <version></version> </plugin> </plugins> </build> <!- -typically used for sub modules The Pom inheritance--> <parent></parent> <!--for the parent module is used to aggregate running the MAVEN project, specifying multiple modules to compile--> &LT;MODULES&G
        T <module></module> </modules> </project>
the dependencies of Maven Dependency Range

Three types of classpath are available in Maven: Compile, test, run.
The scope tag in the Dependency tab specifies the range of current dependencies, which specifies the dependency on the classpath relationship. Simply put, the value under the scope label indicates that the dependency is valid under what stage of the project (except for special values, such as import).
6 optional dependencies are available in Maven:
1. Compile: The default scope, the compilation test run is valid;
2. Provided: Effective when compiling and testing;
3. Runtime: Effective in testing and running;
4. Test: Only when the test is valid;
5. System: Similar to provided, in the compilation and testing of the effective, and associated with the system, portability is poor;
6. Import: A range of imports that can only be used in the scope of the Dependencymanagement dependency to import dependencies for other projects.
Reference:
-Summary of various scope behaviors in Maven Pom
-Use import scope to resolve Maven inheritance (single) problem dependency delivery

In Maven, item a

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.