Maven learning-get started with maven

Source: Internet
Author: User

Maven learning-get started with maven

During Java Development, I came into contact with the Maven build tool. So I spent some time learning about this build tool and the Maven knowledge I learned during the learning process. I will share it with you here.

What is Maven?

First, we need to know what Maven is before introducing Maven.
Maven, in yidi, refers to the accumulation of knowledge. At the beginning, Maven was used as the building tool of Jakarta's Turbine project. Before Maven appeared, different Java projects were built with different Ant configurations, and jar packages were included in the version control system (CVS). There was no unified build tool. If there is a set of tools, you can have a set of standard methods to build a project, and you can clearly define the components of a project, and have a simple method to publish project information, you can share jar packages between different projects. For this purpose, Maven was created.

The initial goal of Maven is to allow developers to quickly understand a project in the shortest period. To achieve this goal, Maven solves the following problems:

  • Make the building process simple
  • Provides a unified building system
  • Provide project-related information
  • New features can be migrated transparently
Use Maven

Before using Maven, make sure that we have installed the Maven build tool. If you have not installed the Maven build tool, refer to the official manual for instructions on how to install Maven.

After Maven is installed, run the following command:mvn -versionView Maven version information:

$ mvn -versionApache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T19:57:37+08:00)Maven home: /usr/local/opt/mavenJava version: 1.7.0_79, vendor: Oracle CorporationJava home: /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/jreDefault locale: zh_CN, platform encoding: UTF-8OS name: "mac os x", version: "10.10.2", arch: "x86_64", family: "mac"

Next, create a new project through Maven.

Create a new Java project using Maven
$ mvn -B archetype:generate \    -DarchetypeGroupId=org.apache.maven.archetypes \    -DgroupId=com.myapp \    -DartifactId=myapp

In the Maven command above, we createdmyappJava project. Once the preceding command is executed, a directory namedmyappProject. The project directory containspom.xmlThe content of the newly created pom file is roughly as follows:

<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.myapp</groupId>  <artifactId>myapp</artifactId>  <packaging>jar</packaging>  <version>1.0-SNAPSHOT</version>  <name>myapp</name>  <url>http://maven.apache.org</url>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>  </dependencies></project>

This pom file indicates the current project'sProject Object Model (POM). In Maven, POM is the basic unit for operations. Maven is centered around the concept of POM to manage the entire project. POM contains important project-related information in the project, and provides dependency management methods similar to the one-stop shopping method, so that you can easily find all dependencies associated with the current project.

The content in the above pom. xml file contains information about the current project. First, let's explain the specific meanings of some elements in the above POM file:

  • projectThis element is the top-level element of the Maven pom. xml file. Each POM file isprojectElement package.
  • modelVersionThis element specifies the version of the project Object Model (pom) used by the current POM. xml file.
  • groupIdThis element indicates the unique identifier of the organization where the project is created. The value of this element is one of the key information for distinguishing a project, the value is usually produced by the reverse write of the domain name of the project's organization (the same as the Java package name mechanism ).
  • artifactIdThis element uniquely identifies the artifact generated by the project (it can be understood as a program generated by code writing, so it can be understood as a manual work ). A project's artifact is generallyjarFile. The format of the final artifact name generated by a project is<artifactId>-<version>.<extension>For example, the artifact generated by the above project ismyapp-1.0.jar.
  • packagingThis element specifies the type of artifact packaging (such as jar, war, and ear ). This does not only mean that the artifact is packaged in any way, but also specifies the specific lifecycle that will be used during the build process (the so-called lifecycle is simply the build process ).packagingThe default value of the element isJAR.
  • versionThis element specifies the version number of the artifact generated by the project. The version number contains the progress of the current project. For exampleSNAPSHOT.
  • nameThis element indicates the project name, which is often used in generated documents.
  • urlThis element indicates the site where the project is located and is often used in generated documents.
  • descriptionThis element provides a description of the project, which is usually used in the generated document.

After a project is created, in addition to the above pom. xml file, a standard directory structure will be generated:

myapp|-- pom.xml`-- src    |-- main    |   `-- java    |       `-- com    |           `-- myapp    |               `-- App.java    `-- test        `-- java            `-- com                `-- myapp                    `-- AppTest.java

The directory structure above is the standard layout of the Maven project. The source code of the project is in the directory${basedir}/src/main/javaDirectory, and the project test code is stored in the directory${basedir}/src/test/javaDirectory. For $ {basedir}, this indicates the directory containing the pom. xml file, that is, the root directory of the project.

Now, we have briefly introduced maven-related concepts and maven standard directory structure. However, before using Maven to build a project, we should first briefly understand the Maven lifecycle.

Maven build Lifecycle

The building mechanism of Maven is built around the concept of lifecycle. This means that the entire process of building and releasing a project is pre-defined. Using this method to build a project allows users to build a project through POM when learning a few commands.

In Maven, there are three built-in build lifecycles:default,clean,site.defaultDeployment of lifecycle processing projects,cleanThe lifecycle process clears the project after it is built,siteThe project's site documentation is generated in the lifecycle.

The Maven lifecycle is composed of different phases (phase. Each lifecycle includes a series of stages, each of which represents a state in the lifecycle. For exampledefaultThe lifecycle includes the following stages:

  • Validate
  • Compile
  • Test
  • Package
  • Integration-test
  • Verify
  • Install
  • Deploy

Maven is executingdefaultDuring the lifecycle, these stages are executed sequentially to complete different tasks.

Build a project using maven

Now we have installed Maven and have some knowledge about Maven-related concepts. Next, we can start to build our project using Maven.

Compile a project

We have createdmyappProject. Now, we can compile this project using the following command.

$ mvn compile

After this command is executed, there will be output similar to the following:

[INFO] Scanning for projects...[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building myapp 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ myapp ---...[INFO] skip non existing resourceDirectory /Users/duke/practise/myapp/src/main/resources[INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ myapp ---[INFO] Changes detected - recompiling the module!...[INFO] Compiling 1 source file to /Users/duke/practise/myapp/target/classes[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 1.159 s[INFO] Finished at: 2015-10-06T18:57:37+08:00[INFO] Final Memory: 11M/156M[INFO] ------------------------------------------------------------------------

After executing this command, Maven will first download all the plug-ins required to build the current project, and all the dependent projects that the current project depends on. From the above output, we can see that the final constructed file is output to the directory.${basedir}/target/classes. One of the advantages of using Maven is that when we follow the Maven conventions, we can use as few configuration as possible to let Maven build projects for us.

Compile unit test

Now, we have successfully compiled our project. Next, let Maven compile and execute unit tests. by executing the following command, Maven can compile and execute the unit tests we have written:

$ mvn test

The preceding command has the following output:

[INFO] Scanning for projects...[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building myapp 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] ...[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ myapp ---[INFO] Nothing to compile - all classes are up to date ...[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ myapp ---[INFO] Changes detected - recompiling the module![INFO] Compiling 1 source file to /Users/duke/practise/myapp/target/test-classes[INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ myapp ---[INFO] Surefire report directory: /Users/duke/practise/myapp/target/surefire-reports------------------------------------------------------- T E S T S-------------------------------------------------------Running com.myapp.AppTestTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 secResults :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 1.799 s[INFO] Finished at: 2015-10-06T19:08:08+08:00[INFO] Final Memory: 13M/156M[INFO] ------------------------------------------------------------------------

From the output, we can see that Maven will first compile before compiling and executing unit tests.mainProject code, and thentestAnd provides a simple report on the unit test results.

Here, we usesurefireThe plug-in executes the unit test.surefireThe plug-in searches for the unit test files that comply with the naming rules agreed by the plug-in and then executes them. By default, files with the following naming rules are executed:

  • **/* Test. java
  • **/Test *. java
  • **/* TestCase. java

Files with the following naming rules are excluded by default.

  • **/Abstract * Test. java
  • **/Abstract * TestCase. java

Of course, if you only need to compile the unit test without executing it, you can run the commandmvn test-comiple.

Project Packaging

Now that we have compiled and tested the project, we need to package the project. In the current projectpackagingThe package type specified in the element isjar. Therefore, we can use the following command to create a jar package:

$ mvn package

The command output is roughly as follows:

[INFO] Scanning for projects...[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building myapp 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------...[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myapp ---[INFO] Building jar: /Users/duke/practise/myapp/target/myapp-1.0-SNAPSHOT.jar[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 1.741 s[INFO] Finished at: 2015-10-06T19:41:05+08:00[INFO] Final Memory: 10M/156M[INFO] ------------------------------------------------------------------------

When executing this command, Maven obtains the packaging type from the pom. xml file, which is the jar package type in this project. Then output the jar to the directory.${basedir}/target.

After packaging, our jar package remains in the target directory of our project. to deploy the jar package to our local repository (the default is~/.m2/repository) For other projects, we need to use the following command to deploy the jar package of the current project to the local repository:

$ mvn install

So far, we have learned how to package and deploy the project to a local repository.

Clear Project

Now, if we need to clean up the created files, we need to use the following command:

$ mvn clean[INFO] Scanning for projects...[INFO]                                                                         [INFO] ------------------------------------------------------------------------[INFO] Building myapp 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ myapp ---[INFO] Deleting /Users/duke/practise/myapp/target[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 0.255 s[INFO] Finished at: 2015-10-06T19:47:25+08:00[INFO] Final Memory: 6M/123M[INFO] ------------------------------------------------------------------------

This command will deletetargetDirectory, because the directory contains all the files output after the project is built. Now, our project is back to the building.

IDE-related commands

If we use the IDE development environment, we can use Maven to generate the IDE description file related to the current project.

For the IntelliJ IEDA environment, you can use the following command to generate:

$ mvn idea:idea

You can use the following command to generate an eclipse environment:

$ mvn eclipse:eclipse
Reference

Http://maven.apache.org/guides/getting-started/index.html

Related Article

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.