From bronze to King, finish Maven with one article and collect it quickly

Posted by ruddernz on Tue, 08 Feb 2022 09:40:19 +0100

Click like and watch again, form the habit of praise, search wechat [coriander Chat Game] and pay attention to me

catalogue

1. What is maven and why does it exist? What is the project structure like and how to locate jar s

2. Operation of Idea

4. Main components of Maven coordinates

5. maven lifecycle

6. Configuration of idea maven

7. POM has two important relationships: aggregation and inheritance

8. profile in Maven

9. maven plugin

10. Environmental variables

11. Maven's two methods of dependency conflict

Summary:

Maven is a package management tool that every Java program will encounter. Today, sort out Maven's relevant knowledge, from bronze to King. Let's start!

1. What is maven and why does it exist? What is the project structure like and how to locate jar s

The official website said a lot. The whole is as complex as it is. Simply put: maven is a tool for managing packages.

What is the necessity of Maven's existence? Considering that there are so many open source jar packages and so many versions, before maven, we managed all jar packages by creating a lib folder after downloading, and then referencing the project. When other project members need to modify a jar, they need to copy it everywhere. It is also troublesome when deploying. Problems need to be solved, so Maven appeared, Unified management, unified warehouse, only need to configure which version of the package to download directly, do not need to copy, is it very convenient.

Now that the big problem has been solved, how to locate a jar package?

2. Operation of Idea

1. New maven project

File - > New - > Project

Check create from prototype (template) and select Maven archetype qiuckstart

Fill in the name of the project and groupId (company domain name, e.g. com.alibaba)

Select the location of the local warehouse and the custom setting configuration

finish all the way, and then wait for idea to create the template project.

2. Configure warehouse

There are three types of Maven warehouses:

  • local

  • central

  • remote

When we execute the Maven build command, Maven starts to find the dependent libraries in the following order:

  • Step 1 - Search in the local warehouse. If not found, perform step 2. If found, perform other operations.

  • Step 2 - Search in the central warehouse. If it cannot be found and one or more remote warehouses have been set, execute step 4. If it is found, download it to the local warehouse for future reference.

  • Step 3 - if the remote warehouse is not set, Maven will simply stop processing and throw an error (unable to find the dependent file).

  • Step 4 - search for dependent files in one or more remote warehouses. If found, download them to the local warehouse for future reference. Otherwise, Maven will stop processing and throw an error (unable to find the dependent files).

Alibaba cloud warehouse configuration:

 <repositories>
       <repository>
           <id>central</id>
           <name>aliyun maven</name>
           <url>https://maven.aliyun.com/repository/public/</url>
           <layout>default</layout>
           <!-- Open release component download -->
           <releases>
               <enabled>true</enabled>
           </releases>
           <!-- Do you want to start the snapshot version Component download -->
           <snapshots>
               <enabled>false</enabled>
           </snapshots>
       </repository>
   </repositories>

3. Add dependency and fastjson dependency

For example:

  <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
       </dependency>

4. Packaged items

4. Main components of Maven coordinates

  • groupId: Organization ID (package name), which is commonly used in the reverse order of company domain names, such as com alibaba

  • artifactId: project name, specific name of the project

  • Version: the current version of the project. Generally, the version number is the larger version Small version Minor version serial number

  • Packaging: the packaging method of the project, including jar and war

5. maven life cycle

5.1 interpretation of terms

  • Lifecycle: life cycle, which is the highest level control unit of maven. It is composed of a series of phases. That is to say, a life cycle is the general name of a large task. No matter how many subtasks it is divided into, running a lifecycle is to explain a task. After running, you get a result and an intermediate process, It is completed by phase. You can define your own lifecycle, including the phase you want

  • Phase: it can be understood as a task unit. A lifecycle is a total task. A phase is a subtask separated from the total task, but these subtasks are normalized. They can be included in multiple lifecycles at the same time. A lifecycle can contain any phase. The execution of phases is sequential. A phase can bind many goals, at least one, Phase without goal is meaningless

  • goal: This is the smallest unit of task execution. It can be bound to any phase. A phase has one or more goals, and the goals are also executed in order. When a phase is executed, the goals bound to the phase will be executed in order according to the binding time. No matter how many goals have been bound to the phase, the goals defined by yourself can continue to be bound to the phase

  • Mojo: life cycle, phase and goal are conceptual things. Mojo does specific things. You can simply understand that mojo is the implementation class of goal. It inherits from AbstractMojo and has an execute method. The definition of goal is realized by defining some annotated anotations in mojo. maven will automatically generate some xml files according to these anotations when packaging, Put it in the jar package of the plugin

It can be popularly understood that lifecyle is a company, phrase is a specific department, goal is a project, Mojo is a person within the project, and others are management levels. The specific implementation is still a person.

5.2 life cycle

5.3 the concept of goal

A goal is independent. It can be bound to multiple phase s or none. If a goal is not bound to any lifecycle, it can still be called directly instead of by the lifecycle.

Therefore, the relationship between phase and goal can be understood as follows:

  1. Phase is actually the container of goal. What is actually executed is goal. When a phase is executed, the actual execution is the goal bound to the phase.

  2. Goal and goal are independent. Therefore, executing one goal alone will not cause other goals to be executed.

It can be understood as a popular project.

5.4 relationship between life cycle and phase

Clean life cycle each set of life cycle is composed of a set of phases. The commands we usually enter on the command line always correspond to a specific phase. For example, run mvn clean, which is a stage of the clean life cycle. There are both clean life cycle and clean phase. The clean life cycle consists of three phases:

  1. Pre clean performs some work that needs to be done before clean

  2. clean removes all files generated by the last build

  3. Post clean performs some work that needs to be done immediately after clean

The clean in "mvn clean" is the above clean. In a life cycle, when running a certain stage, all the previous stages will be run. That is to say, "mvn clean" is equivalent to MVN pre clean clean. If we run MVN post clean, both pre clean and clean will be run. This is a very important rule of Maven, which can greatly simplify the input of the command line

Executing phase actually executes goal. If a phase is not bound to goal, the phase will not be executed.

<plugin>
  <groupId>com.mycompany.example</groupId>
  <artifactId>display-maven-plugin</artifactId>
  <version>1.0</version>
  <executions>
    <execution>
      <phase>process-test-resources</phase>
      <goals>
        <goal>time</goal>
      </goals>
    </execution>
  </executions>
</plugin>

A life cycle contains a number of steps. When the life cycle is executed, all steps will be executed once

Official documents:

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

http://maven.apache.org/ref/3.3.9/maven-core/lifecycles.html

6. Configuration of idea maven

The following configurations can be specified in POM:

  • Project dependencies

  • plugins

  • Implementation objectives

  • Project build profile

  • Project version

  • Project developer list

  • Related mailing list information

For specific configuration, refer to fastjson configuration:

https://github.com/alibaba/fastjson/blob/master/pom.xml

7. POM has two important relationships: aggregation and inheritance

1, Aggregate

If we want to build multiple project modules at one time, we need to aggregate multiple project modules

1. Aggregation configuration code

<modules>
      <module>Module I</module>
      <module>Module II</module>
      <module>Module III</module>
</modules>

For example: aggregate the three modules of Hello, hello friend and MakeFriends of the project

<modules>
      <module>../Hello</module>  
      <module>../HelloFriend</module>        
      <module>../MakeFriends</module>
</modules>

The path of module is relative.

2, Inherit

Inheritance in order to eliminate duplicate configurations, we extract many of the same configurations, such as grouptId, version, the same dependent package, etc.

Inherited configuration code:

<parent>  
         <groupId>me.gacl.maven</groupId>
         <artifactId>ParentProject</artifactId>
         <version>0.0.1-SNAPSHOT</version>
         <relativePath>../ParentProject/pom.xml</relativePath>  
</parent>

In Idea, you can create a maven project and delete all the folders, leaving only one POM XML, then add the module and select inheritance.

 

8. profile in Maven

  • Maven has a concept called profile, which is mainly used to solve the problems of different variables and configurations required by different environments. For example, the database configuration and port configuration developed by our intranet are different from the production environment, which needs to be distinguished at this time.

  • With a profile, you can start the configuration information under different conditions according to the activation conditions.

  • There can be multiple profiles, or multiple profiles can be activated at the same time, which is convenient for free combination.

<profiles>
       <profile>
           <!--Different environment Profile Unique id-->
           <!--development environment -->
           <id>dev</id>
           <properties>
               <!--profiles.active It is a user-defined field (any name). There can be multiple user-defined fields-->
               <profiles.active>dev</profiles.active>
           </properties>
       </profile>
       <profile>
           <!--Online environment-->
           <id>prod</id>
           <properties>
               <profiles.active>prod</profiles.active>
           </properties>
           <activation>
               <activeByDefault>true</activeByDefault>
           </activation>
       </profile>
   </profiles>

Two configured profile s will be displayed in Idea, which can be activated

 

The configuration in pom file is

<build>
       <resources>
           <resource>
               <directory>src/main/resources/</directory>
               <!--Exclude two folders first-->
               <excludes>
                   <exclude>dev/*</exclude>
                   <exclude>prod/*</exclude>
               </excludes>
               <includes>
                   <!--If there are other general definition documents, they need to be included-->
                   <!--<include>messages/*</include>-->
               </includes>
           </resource>
           <resource>
               <!--Here is the key! Package the configuration files in the corresponding folder according to different environments-->
               <directory>src/main/resources/${profiles.active}</directory>
           </resource>
       </resources>
   </build>

  <profiles>
       <profile>
           <!--Different environment Profile Unique id-->
           <!--development environment -->
           <id>dev</id>
           <properties>
               <!--profiles.active It is a user-defined field (any name). There can be multiple user-defined fields-->
               <profiles.active>dev</profiles.active>
           </properties>
       </profile>
       <profile>
           <!--Online environment-->
           <id>prod</id>
           <properties>
               <profiles.active>prod</profiles.active>
           </properties>
           <activation>
               <activeByDefault>true</activeByDefault>
           </activation>
       </profile>
   </profiles>

9. maven plugin

  1. Maven's core only defines the abstract life cycle, and the specific tasks are completed by plug-ins.

  2. Each plug-in can realize multiple functions, and each function is a plug-in target goal.

  3. Maven's life cycle is bound to the plug-in goal to complete a specific construction task. For example, compile is a plug-in goal of the plug-in Maven compiler plugin.

Common plug-ins:

maven-antrun-plugin

maven-archetype-plugin

maven-assembly-plugin

maven-dependency-plugin

maven-enforcer-plugin

maven-help-plugin

maven-release-plugin

maven-resources-plugin

maven-surefire-plugin

build-helper-maven-plugin

exec-maven-plugin

jetty-maven-plugin

versions-maven-plugin

10. Environmental variables

${basedir} represents the root directory of the project, which contains POM Directory of XML files;

${version} indicates the project version;

${project.basedir} is the same as ${basedir};

${project.baseUri} indicates the address of the project file;

${maven.build.timestamp} indicates the start time of the project component;

${maven.build.timestamp.format} represents the display format of the attribute ${maven.build.timestamp}. The default value is yyyymmdd HHMM. Its format can be customized, and its type can refer to Java text. SimpleDateFormat.
${project.build.directory} indicates the main source code path;

${project.build.sourceEncoding} represents the encoding format of the main source code;

${project.build.sourceDirectory} indicates the main source code path;

${project.build.finalName} indicates the name of the output file;

${project.version} represents the project version, which is the same as ${version};

${project.xxx} contents of any node of the current pom file
${env.xxx} gets the system environment variable.
${settings.xxx} refers to settings The value of the corresponding element in the XML.

 

11. Maven's two methods of dependency conflict

1. Unified version

Use dependency management for version locking. Dependency management can uniformly manage the version number of the project to ensure that the dependency and version of each application project are consistent.

If we only want to use the package of spring core 5.2.0 in our project, POM XML can be changed as follows

<dependencyManagement>
       <dependencies>
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-core</artifactId>
               <version>5.2.0.RELEASE</version>
           </dependency>
       </dependencies>
   </dependencyManagement>

   <dependencies>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.2.7.RELEASE</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-aop</artifactId>
           <version>5.2.0.RELEASE</version>
       </dependency>

   </dependencies>

2. Exclude dependencies

Two principles of dependency lookup:

Use the principle of "path closer first": direct dependency is higher than transitive dependency.

Use the first declarant first principle: whoever defines it first will use the delivery dependency of who, that is, in POM From top to bottom, the XML file first declares the jar coordinates, and then refers to the transfer dependency of the jar.

Idea can install maven helper plug-in to resolve conflicts.

maven helper plug-in is installed successfully. Click POM XML will find an additional Dependency Analyzer view. The icon of the button above has the following meanings

  • Conflicts (view conflicts)

  • All Dependencies as List

  • All Dependencies as Tree

The above figure shows that there are three jars in conflict. Click the conflicting jar to see which jar conflicts with, as shown in the following figure

Click on POM XML, switch to the Dependency Analyzer view, select All Dependencies as Tree, click the jar to be excluded, and the exit option will appear by right clicking, as shown below

 

Summary:

Maven is a common tool in development, which is very important, so try to master it as much as possible.

What else do you know about Maven? Welcome to leave a message!!!

Don't hurry to praise!!!

Topics: Java Android IntelliJ IDEA Maven Spring