Idea operation Maven detailed use

Posted by dokueki@gmail.com on Fri, 14 Jan 2022 13:30:14 +0100

Idea operation Maven detailed usage:

Introduction to Maven

What is Maven

Maven's correct pronunciation is[ ˈ mev Ι™ n] "Sell v", not "horse plague" and other plagues.
Maven is a project management tool, which contains a project object model (POM), a set of standards.

What problems can Maven solve

Now we need to use many third-party class libraries Jar packages to build a project
If you write a Web project using Spring, you need to introduce a large number of jar packages,
Often, a Jar package will refer to other Jar packages. The lack of any Jar package will lead to project compilation failure.
Each development project will require a large number of Jar packages. An ordinary Java project may have only a few MB or even KB of actual source code, but with Jar, it may be dozens of MB.
For the same project, if we use Maven project to build, the overall size of the project will be much smaller. Deploy to server

**Maven is a tool to help programmers build projects. We just need to tell Maven which Jar packages they need,
It will help us download / provide all jars and greatly improve development efficiency**

Maven has two classic functions:

Dependency management ~ is to manage jar packages (related to warehouse knowledge, which will be described below)~

A core feature of Maven is dependency management.
When we are involved in multi module projects (including hundreds of modules or subprojects), managing dependencies becomes a difficult task. Maven shows a high degree of control in dealing with this situation.
In the traditional WEB project, we have to copy the jar package that the project depends on into the project, which leads to the great of the project.
So how does maven project make engineering rare?
Idea common Maven project directory:

In maven project, the jar package is not directly imported into the project, but through POM Add the coordinates of the required jar package to the XML file.
In this way, it is very good to avoid the direct introduction of jar and make the project larger πŸ™ƒπŸ™ƒπŸ™ƒ~
When you need a jar package, you can use POM Coordinates in XML file
Go to a special "maven warehouse" for storing jar packages. Find these jar packages according to the coordinates and run them.
Moreover, the process does not need to worry about finding jar packages in the warehouse, which will affect the program performance:
maven also has the concept of index, which can greatly improve the speed of loading jar packages,
This makes us think that the speed of jar package is basically the same as that of reading it in the local project file.
”What does the "repository" for jar packages look like?
Warehouse, as the name suggests, is the place where some necessary grain (jar bags) for the project are stored. Warehouses in Maven are divided into three categories:

Local warehouse:
Stored in the local server, when running the project, maven automatically searches the local warehouse according to the configuration file and then uses the jar package from the local warehouse.
Remote warehouse (private server):
When there is no jar package required by the project in the local warehouse, maven will continue to find the remote warehouse. Generally, the remote warehouse refers to the private server built by the company, also known as the private server;
When the jar package is found in the private server, maven will download the jar package to the local warehouse. When it is used next time, there is no need to go to the remote warehouse.
Central warehouse:
When the remote warehouse cannot obtain the jar package, you need to go to the central warehouse to find it and download it in the remote warehouse, and the local warehouse will download it back from the remote warehouse for use.
**This is maintained by maven team. It is said that as of 16 years, there have been 200 million packages in the warehouse!
It can be said that all the packages we need come from the central warehouse. We don't need to worry about the absence of jar packages**

One click construction

The whole process of compiling, testing, running, packaging, installing and deploying the project is managed by maven. This process is called build.
One click Construction: refers to the whole construction process. The whole work can be easily completed by using maven commands.
Maven's standardized construction process is as follows:

It's good to know this at present. Let's explain ~ feelings in detail in combination with project examples;

IDEA uses Maven project:

My idea is in Chinese, and students with different version 1.3 can understand it more~ πŸ˜„
be careful! It's best to use Maven project when there is a network. For some components, Jar should be downloaded online

First, idea configures maven's installation directory and local repository

Every time Idea creates a new Maven, it is recommended to take a look, otherwise the local resource library is wrong, and Jar randomly places it for download Not good~
File - set value - input Maven in the input box

Start the project!!

Create Maven project: ~ file - New - Project~

Next (here I will build a common project to understand Maven life cycle)

study web It may take a long time to download the project...Just wait slowly~ Know to appear Src **Network card this kind of thing is very helplessπŸ˜₯**  Finish

This is a good project I created. Do you think there are any shortcomings.


Idea's tools are not perfect. For some files, the creation is incomplete and can be completed by yourself: it is basically the structure shown in the figure above
Manually create a resources file under the test file: and identify it as a resource file through the tool
But note: the target file is not created manually!!! Maven project life cycle automatically generated Mainly used to store: compiled files.

After the above series of operations, a conventional Maven project has been created:

||--- the main code of the main project
||--- java ---- the source file of the project
|resources -- store project resource files, such as spring and Hibernate configuration files
||--- the directory used to test the project code is equivalent to the directory of Junit's test code
|java -- store all tests java files, such as JUnit test classes
|resources -- store project test resource files, such as spring and Hibernate configuration files

Create a package com. In the Main - Java Directory: Text. Under WSM package Jave suggested adding bags!!

public class Text {
    public void show(){
         System.out.println("Hello World");
    }
}
// This is a very simple and common section of Jave code ~ no one can't understand it πŸ˜„

Create a package com. Under Test - Java Directory: Ttest.wsm package Jave
Mainly used to test whether the above source code can run normally Don't think if there is any special function, that's it!

import org.junit.Test;
public class TTest {        //The class name must end with Test (I'm really speechless. I don't know this has been adjusted for a long time...)
    @Test                   //Junit note: this method is used for unit testing (the Jar coordinates need to be introduced into Junit Package ~ Pom.xml)
   public void testShwo(){  //The method name should start with test, and the specification
        //Declare the class in the source code and call show(); Test results~
        Text t = new Text();
        t.show();
    }
}

pom.xml
This is just the basic tag attribute, because it is basic and there are too many I'm lazy πŸ™ƒ

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

    <!-- Specify current pom Version of the model, maven2 And 3 are both 4 -->
    <!-- Pom Files can be used for decoupling to maximize the difference between projects -->
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>                  <!-- Define which company and department group the project is -->
    <artifactId>MavenWSM</artifactId>               <!-- Unique within group id(For example, which component in the project:Module name,Maven Module development can be realized~) -->
    <version>1.0-SNAPSHOT</version>                 <!-- Current version of the project,SNAPSHOT Is an unstable version(Rapid development) -->
    <!-- groupId  artifactId  version:It also determines the packaging of the project/Styles for publishing files/Address: under the local warehouse/org/example/MavenWSM/1.0-SNAPSHOT/MavenWSM-1.0-SNAPSHOT.jar  -->
    <name>WSM</name>                                <!-- Project Alias  -->
    <packaging>jar</packaging>                      <!-- Component types generated by project packaging,for example jar,war,ear,pom... Commonly used Jar(default) war -->
    <!--Jar: Generally, it is convenient for companies to make their own,Develop invoked components Jar...     war: Package project into war Can be deployed to the server to run...Format of;  Not here web Engineering, so it's not necessary war jar that will do~ -->

    <!-- by pom Define some constants in pom Other parts of the can be directly referenced and used as follows: ${project.build.sourceEncoding} -->
    <properties>
        <!-- Unified project character set encoding: Underlying references ${project.build.sourceEncoding} Unified character set  -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- Set value jdk code,This method is the of the specified project JDK Version or in Maven settings.xml Configuring a unified environment in JDK  -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>


    <!-- The description of all dependent packages is stored in,That is, provide the coordinates of the download -->
    <dependencies>
        <!-- every last dependency Describe a Jar coordinate: Go to the local place to find -- can't find the private server to download -- go to the local place to download the private server without going to the central warehouse.. -->
        <dependency>
            <groupId>junit</groupId>            <!-- Company group -->
            <artifactId>junit</artifactId>      <!-- project/jar/Module name -->
            <version>4.9</version>              <!-- edition -->
            <scope>test</scope>                 <!-- Jar Scope of package use: The default usage range is compile,This code can be used by both test code and main code; -->
       <!-- <scope>system</scope>               <systemPath>introduce Jar Resource path...</systemPath> -->
        </dependency>
        <!-- Omit other more Jar Package coordinates.... -->
    </dependencies>
    
    <!-- build Maven Plug in for
    This element sets the project source directory,When building a project,The build system will compile the source code in the directory.-->
    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <!-- Like the above functions, they are all set values JDK Version of~ Just set any value; -->
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
    </build>

</project>

Pom.xml explanation: Here I will expand and update from time to time~

  1. dependencies -- > dependency -- > = = scope dependency range==

    A depends on B and needs to be in the POM of A Add the coordinates of B in the XML file. When adding coordinates, you need to specify the dependency range, which includes ↓↓
    compile: compilation range, the default range value. Dependencies will be used for compilation, testing and running. Because they are required at runtime, the dependencies of the compilation range will be packaged.
    Provided: the compilation scope. Provided depends on what is required during compilation and testing, but not during runtime. For example, servlet api runtime is provided by tomcat container. (conflicts will report errors instead!)
    runtime: the compilation scope, which depends on the need when running and testing the system, but not when compiling. For example: jdbc driver package.
    Test: the compilation scope is not required during compilation and running. They are only available during test compilation and test running. For example: junit.
    system: compilation range. system range dependency is similar to provided. Jar s using paths other than local paths need to specify systemPath disk path (not recommended!)
  2. Source method of coordinates:
    Search from the Internet: 1 http://search.maven.org/ 2.http://mvnrepository.com/
    In this way, you don't have to look for Jar everywhere. You can directly find the coordinates in Maven and download them locally!
    Copy from other students' local database is also a way. Directly copy the whole warehouse and change the Setting configuration file~

Run test: one click build using Maven

   **We can go directly to cmd Through a series of maven command:**
   To our**MavenWSM Project progress:** Clean up compilation, testing, running, packaging, installation and deployment.

Find the local path of the project:
You can use the copy path in the idea tool - Windows+r: copy and press enter to quickly open the file;
Enter "cmd" in the file path to enter the file path to facilitate the operation of Maven command; (or you can manually cd: find the switching path..)

Maven common commands
cmd enters the command state and executes mvn compile, as shown in the following figure, indicating success:
Compile is the compilation command of maven project. It is used to compile the files under src/main/java into class files and output them to the target directory.
Then the target folder will appear in your project: compiled code
BUILD SUCCESS compiled successfully!
cmd executing mvn clean will delete the target directory and contents, and clean up.
cmd execute mvn test execute unit test classes under src/test/java
cmd executes mvn package, generates jar package for java project and war package for web project. And will include the test operation;
cmd execute mvn install execute install to print maven into jar package or war package and publish it to the local warehouse. Including package and test operations;
cmd executes mvn deploy. Deploy prints maven into jar packages or war packages and publishes them to local warehouses and private servers. Including package test install operation;
cmd executes mvn clean test. Clean up the test first
The Idea tool can directly double-click the corresponding life cycle:

Final project structure:

Write Maven project. It is suggested that each source code under main must have a package! Because the project packaging package publishes install Is to package the source files under main~
If there is a separate file without a specified package, it will be placed in the META-INF directory by default. Students who have studied JSP know that the files in this directory are read-only and non adjustable
This is Maven's one click build. Isn't it super interesting!!

Maven operation Web project:

Please create a web project according to the above case:
If the creation process is too slow, you can learn from it: adding: archetypecatalog | internal during creation will be much faster. Pay attention to the Maven model

The general structure is as follows:

The src/main/jave folder is not complete. You also need to manually add the src/main/jave folder (and modify the type of the corresponding folder, Jave source file type, resource file type...)
Final Web structure:

index.jsp
The default JSP of Idea tool does not conform to the specification, so change it yourself~

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>first maven engineering</title>
</head>
<body>
Hello World!
</body>
</html>

After that, configure Tomcat of Idea, build the project Package war package through Maven, and deploy it to the project ~;

ok, just sauce! No need to modify any code ~ if Idea starts the service, the program will be loaded automatically
If you deploy those projects in the current server, you can execute those projects. Even if you have existing projects locally, you can't access the server without deploying Idea configuration~

The Maven project uses custom jar s

ok, here, the web project will be finished
As for me, I'm in main -- java -- com wsm. Test - cs is my test Demo
Normally, it says: Dao entity service comroller Program code (SSM SSH), don't be confused by yourself~

This test: one Maven project introduces another Maven project program: realize module development

pom.xml plus

    <!-- Remember this? A common resource reference, But!
        Watch carefully,This is the version of the group module name just written... 
        Maven install Package project Jar To local,other Maven Items can be directly dependency Introduction and use,Class of the project/method~
        Does it feel more and more advanced....Now you can develop it yourself Jar Convenient for future development and use~
    -->
    
  </dependencies>
    <dependency>
      <groupId>org.example</groupId>
      <artifactId>MavenWSM</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
  </dependencies>

cs.java

import com.wsm.Text;   //Here's com wsm. Text is the package to import the project. If there is no package, the file exists MATE - INF cannot be imported! (therefore, it is recommended that the source code be placed under the package ~ a specification!)
public class CS {
    public static void main(String[] args) {
        //Create the class object in the custom Jar package and call the method ();
        Text text = new Text();
        text.show();
    }
}

Right click directly, run! “Hello World”

Maven installation:

Please click.

Finally, I'm finished. Please praise me πŸ‘ Ah!

Topics: Maven IDEA