Maven | Efficiently manage and build Java projects (installation, configuration and basic use of Maven tools)

1. Introduction to Maven

Maven is a tool specially used to manage and build Java projects. Its main functions are:

  • Provides a standardized project structure
  • Provides a standardized build process (compile, test, package, release...)
  • Provides a set of dependency management mechanisms

1.1 Standardized project structure

Project structure We all know that each development tool (IDE) has its own different project structure, and they are not common to each other. The project structure I Eclipsecreated in the software cannot IDEAbe used in the software, which caused great inconvenience. As shown in the figure below: the last two are development tools that are often used in future development.

Maven provides a set of standardized project structures. All development tools use Maven to build project structures that are exactly the same, and Maven projects created by all development tools can be used universally. The right side of the figure below is the project structure built using Maven.

1.2 Standardized project construction process

As shown in the figure above, we have built a project. The code of the project needs to go through the process of compiling, testing, packaging, and publishing . If these operations need to be repeated, it will be particularly troublesome. Maven provides a set of simple commands to complete the project construction. .

1.3 Dependency management

Dependency management , in fact, is to manage what the project depends onThird-party resources (for example, jar packages, plug-ins, etc.). In our previous projects, we needed to use the technology of JDBCconnecting to Druidthe database and the technology of obtaining the database connection pool. These required downloading the corresponding dependent packages from the Internet, copying them to the project, and adding the dependent packages to the working environment of the project. This series of operations is shown in the figure below:

while Maven uses the standardcoordinateConfigure to manage various external dependencies, only need a simple configuration to completedependency management

As shown on the right side of the figure above, it isMySQL databaseThe coordinates of the jar package , in the Maven project, we only need to write this coordinate configuration in the configuration file , and we don’t need to worry about other things, Maven will help us import the coordinatesMySQL databasejar package.

There are many project construction tools on the market, but Maven is still the mainstream construction tool. The figure below shows the usage ratio of commonly used construction tools.

insert image description here

1.4 Introduction to Maven

Apache Mavenis a project management and buildtool, which is based on the concept of the project object model ( POM), manages the construction, reporting and documentation of projects through a small piece of descriptive information.

Maven official website: http://maven.apache.org/

Through the above description, you only need to know that Maven is a tool. Apache is an open source organization, and we will learn many projects provided by Apache in the future.

1.4.1 Maven model

The models included in Maven are as follows:

  • Project Object Model ( Project Object Model)
  • Dependency Management Model ( Dependency)
  • plugin ( Plugin)

As shown in the figure below, it is the model diagram of Maven . Let's first look at the part framed by the purple frame (build life cycle), this part is used to complete the standardized build process . If we need to compile the project, Maven provides a compilation plugin for us to use; if we need to package the project, Maven provides a packaging plugin for us to use and so on.

The part framed by the purple box in the figure below, the project object model is to abstract our project into an object model, with its own exclusive coordinates . The dependency management model uses coordinates to describe which third-party packages the current project depends on jar.

As shown in the figure below, it is a Maven project. The part framed in red is our project and the object model abstracted by Maven, that is, the coordinates .

As shown in the figure below, <dependencies>the content in the label is the dependency management model provided by Maven . It uses coordinates to describe which third-party jarpackages , and each jarpackage corresponds to a subtag <dependency>.

insert image description here

And the last part of the Maven model diagram above is the warehouse . How to understand the warehouse? Then look down:

1.4.2 Warehouse

Let’s think about this scenario. We create a Maven project and use coordinates in the project to specify the third-party dependencies (jar packages) of the project. So where are the jar packages stored? The answer is stored in our local repository . When the project is running, the required jar package will be obtained from the local warehouse .

Warehouses are categorized as follows:

  • Local warehouse : It is a local directory on your own computer.
  • Central warehouse : The only warehouse in the world maintained by the Maven team.
  • Remote warehouse (private server) : Generally, a private warehouse built by a company team.

Today we only studyremote warehouseThe use of , does not need to build a warehouse.

When coordinates are used in the project to import the corresponding dependent third-party jar package, the project will first go tolocal warehouseFind whether there is a corresponding jar package in:

  • If so, directly reference the jar package in the project;
  • If not, it will go to the central warehouse to download the corresponding jar package to the local warehouse, and then the project will reference the jar package from the local warehouse.

As shown below:

If we also set up a remote warehouse , then the search order of jar packages in the future will become:

  • Local Warehouse --> Remote Warehouse --> Central Warehouse

That is, the item will first go tolocal warehouseCheck whether there is a corresponding jar package in the , if not, it will go toremote warehouseFind whether there is a corresponding jar package in , if so, download the corresponding jar package to the local warehouse, and then the project will reference the jar package from the local warehouse; ifremote warehouseIf not, will gocentral warehouseDownload the corresponding jar package to the local warehouse, and finally the project references the jar package from the local warehouse.

As shown below:

insert image description here

2. Maven installation configuration

2.1 Download and install

First go to Maven's official website to download and install the compressed package, and decompress apache-maven-3.6.1-bin.zipthe compressed package to a local directory.

It is recommended to decompress to a path without Chinese or special characters. As in this article, the blogger unzips it to D:\softwarethe directory .

The directory structure after decompression is as follows:

  • binDirectory: Stores executable commands. mvnCommands require focused attention.
  • confDirectory: store Maven configuration files. settings.xmlThe configuration file needs to be modified later.
  • libDirectory: store the jar packages that Maven itself depends on. Maven is also a tool developed in Java, so it also depends on other jar packages.

2.2 Configure environment variables

Configure the environment variable MAVEN_HOMEas binthe directory of the installation path

  • Right click on My Computer --> Advanced System Settings --> Advanced --> Environment Variables

The first step is to create a new variable at the system variable MAVEN_HOME, and set the variable value to the path where Maven is located. As shown below:

The second step is to edit the variables in the system variables PATH. As shown below:

The third step is to open the command prompt for verification. If the page shown in the figure below appears, it means the installation is successful .

2.3 Configure local warehouse

1. conf/settings.xmlModify <localRepository>the tag in the file and specify a local disk directory as Maven's local warehouse to store third-party jar packages. As shown below:

2. Configure Alibaba Cloud private server

Since the central warehouse is abroad, the speed of downloading the jar package may be slow. Ali Company provides a remote warehouse , which basically has jar packages commonly used in open source projects, so we can use Ali's remote warehouse to download jar packages.

conf/settings.xmlModify <mirrors>the contents of the tag in the file and add the following sub-tags:

<mirror>
      <id>aliyunmaven</id>
      <mirrorOf>*</mirrorOf>
      <name>阿里云公共仓库</name>
      <url>https://maven.aliyun.com/repository/public</url>
</mirror>

3. Use Maven to build the project in IDEA

In future development, we will definitely use Maven in advanced development tools to manage projects, and our commonly used advanced development tools are IDEA, so next we will explain the use of Maven inIDEA .

3.1 IDEA configures the Maven environment

We need to configure the Maven environment in IDEA first:

The first step, select IDEAFile --> Settings

The second step, search for maven

The third step is to set IDEA to use locally installed Maven, and modify the Maven configuration file path to the path where our own configuration file is located:

3.2 Detailed explanation of Maven coordinates

1. What are coordinates?

  • The coordinates in Maven areA unique identifier for the resource
  • Use coordinates to define projects or import third-party resources (jar packages) needed in projects .

2. 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.example).
  • artifactId : Defines the current Maven project name (usually the module name, eg: order-service、goods-service).
  • version : Defines the version number of the current project.

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, other projects also need to introduce our project through coordinates.

3.3 Using IDEA to create a Maven project

The first step is to create a new module, select Maven, and clickNext

The second step is to fill in the module name, coordinate information, and click finishto complete the creation

The directory structure of the created Maven project is as follows:

insert image description here

The third step is to write a Java program and run it. omitted here


3.4 Use IDEA to import Maven project

You may need to import other people's Maven projects into your own IDEA in normal times. We can import Maven projects through the following steps:

Suppose I want to import maven-projectthis Maven project.

The first step is to select the Maven panel on the right side of the IDEA interface and click the + sign

pom.xmlThe second step is to select the file of the Maven project you want to import and double-click it.

In the third step, if there is no Maven panel on the right side of the interface, you can choose it View --> Appearance --> Tool Window Bars. In this way, you can see the Maven panel of the interface. Then use the above steps to import the Maven project.

Supplement: We can perform shortcut operations on Maven projects through the Maven panel provided by IDEA. As shown in the figure below, we can perform command operations on it (double-click):


3.5 Configure the Maven-Helper plugin

The first step, select IDEA inFile --> Settings

Step two, choosePlugins

The third step is to search for Maven, select the first one Maven Helper, click InstallInstall, and click in the pop-up panelAccept

The fourth step, restart IDEA

After installing the plug-in, you can select the item and right-click to perform shortcut operations of related commands, as shown in the following figure:

4. Basic usage of Maven

4.1 Maven's common commands

  • compile: compile
  • clean: clean up
  • test:test
  • package:Pack
  • install:Install

4.1.1 Command Demo

1. Create a project built with Maven, the project structure is as follows:

2. If we want to use the above command, we need to enter the pom.xmlfile and use the command prompt:

4.1.2 Demonstration of compiling commands:

compile :编译

Execute the command in the command prompt compileto see:

  • Download the jar package of the plug-in required to compile the project from Alibaba Cloud, and you can see the downloaded plug-in in the local warehouse.
  • A targetdirectory .

1. Download the jar package of the plug-in required to compile the project from Alibaba Cloud, and you can see the downloaded plug-in in the local warehouse. As shown below:

2. At the same time, a targetdirectory , and the bytecode files compiled by the project will be placed in this directory:

4.1.3 Cleanup command demo

mvn clean:清理

Execute the command in the command prompt mvn cleanto see:

  • Download the plug-in jar package required for cleaning from Alibaba Cloud.
  • targetThe directory under the project is deleted.

Download the plug-in jar package required for cleaning from Alibaba Cloud. As shown below:

4.1.4 Packaging command demonstration

mvn package:打包

Execute the command in the command prompt mvn packageto see:

  • Download the plug-in jar package required for packaging from Alibaba Cloud.
  • There is a jar package under the project tergetdirectory (the jar package that makes the current project).

Download the plug-in jar package required for packaging from Alibaba Cloud, as shown in the following figure:

4.1.5 Test command demo

mvn test:测试

Execute the command in the command prompt mvn testto see:

  • This command will execute all test code in the project.

The effect is as follows:

4.1.6 Installation command demo

mvn install:安装

Execute the command in the command prompt mvn installto see:

  • This command willcurrent projectinto a jar package, andInstall to local repository

After executing the above command, go to the local warehouse to view the results as follows:

4.2 Maven life cycle

Maven builds the project life cycle, which describes how many events a project's build process has experienced.

Maven divides the life cycle of project construction into 3 sets:

  • clean: Clean up jobs.
  • default: Core work, such as compilation, testing, packaging, installation, etc.
  • site: Generate reports, publish sites, etc. This set of statement cycles is generally not used.

In the same set of life cycle, execute the following commands,All the previous commands will be executed automatically. For example under the default ( default) life cycle:

  • When we execute installthe (install) command, it executes compilethe command , then test the command, then packagethe command , and finally installthe command.
  • When we execute packagethe (package) command, it executes compilethe command , then testthe command, and finally packagethe command .

The default life cycle also has many other commands, but they are generally not used. We only focus on the commonly used ones. The commands with red icons are as follows:

5. Dependency Management in Maven

5.1 Use coordinates to introduce third-party jar packages into Maven projects

5.1.1 Find the corresponding jar package on the official website

Steps to import jar package using coordinates:

  • Write tags in your project's pom.xmlconfiguration file <dependencies>.
  • <dependencies>Use subtags in tags <dependency>to bring in coordinates.
  • define the coordinates groupId,artifactId,version.

The following figure shows the jar package we introduced into MySQLthe database:

Note: pom.xmlAfter introducing a new third-party jar package in the file, remember to click on the upper right cornerrefresh button, to make the imported coordinates take effect. If you do not click the refresh button, sometimes the import may not be successful. As shown below:

Notice:

  • For the coordinates of the specific third-party jar package, we can go to the following website to search:
  • https://mvnrepository.com/

5.1.2 Shortcut to import the coordinates of the jar package

Every time you need to import a jar package, it is troublesome to go to the corresponding website to search. Next, I will introduce a quick way to import jar package coordinates.

The first step is to press the shortcut key in pom.xmlthe file alt + insertand selectDependency

The second step is to search for the coordinates of the jar package you want to import in the pop-up panel, and then double-click to select the corresponding coordinates

The third step is to click the refresh button to make the coordinates take effect:

Supplement: Automatically import coordinate settings (not recommended)

Each of the above operations of importing coordinates needs to click the refresh button to make the imported coordinates take effect. Of course, we can also automatically import it through IDEA settings, without additionally clicking the refresh button. Proceed as follows:

  1. Select IDEAFile --> Settings

  1. In the pop-up panel findBuild Tools

  1. Select Any changesand click okto take effect.

5.2 Dependency scope

By setting the coordinates ofDependency scope( scope), you can set the scope of the corresponding jar package: compilation environment, test environment, and running environment.

As shown in the figure below, specify the scope of the dependency for the coordinate junitdependency of the jar package through <scope>the tag . Then this dependency can only be used in the test environment, and cannot be used in other environments.

So what are the values ​​of <scope>the tags ? The form is as follows:

Dependency scope compile classpath test classpath run classpath example
compile Y Y Y logback
test - Y - Junit
provided Y Y - servlet-api
runtime - Y Y jdbc driver
system Y Y - jar package stored locally
  • compile: Acts on the compilation environment, test environment, and runtime environment .
  • test: Act on the test environment . The typical one is Junitthe coordinates, Junitwhich will be <scope>specified as this value when used later.
  • provided: Acts on the compilation environment and test environment . We will learn later servlet-apithat when using it, must be <scope>set to this value, otherwise an error will be reported at runtime.
  • runtime: Applicable to the test environment and the running environment . jdbcThe driver generally <scope>sets to this value, and of course there is no problem if it is not set.

Note: If the imported coordinates do not specify <scope>the label , the default is compilethe value, which is applied to the compilation environment, test environment, and running environment. In the future, most of the jar package coordinates will use the default value.

Guess you like

Origin blog.csdn.net/weixin_45395059/article/details/129779809