Use of Maven tools

Posted by BillyMako on Thu, 20 Jan 2022 10:58:49 +0100

1, What is Maven?

Maven is a build tool plug-in used to manage java packages. It solves the cumbersome operation of manually copying jar packages to the WEB-INF/lib directory or BOOT-INF/lib directory in the traditional development mode. When a project is large, it is no longer suitable to use package to divide modules, but use engineering to divide modules. As a module is a project, different projects need to rely on each other.

With maven, we can split a large project into multiple projects. When we need to rely on jar packages, we only need to reference them in the pom file. When the project is packaged, the imported jars will be automatically packaged into the WEB-INF/lib directory or BOOT-INF/lib directory. Jar usually has chain dependency, and the jar package you depend on may depend on other jar packages, which is undoubtedly painful for manually solving jar dependency. These problems are easily solved in Maven project. He will automatically download all dependent jars to the local warehouse for use according to the pom file in the jar package.

Construction refers to the process of generating a running project with java source files, framework configuration files, JSPS, html, pictures and other resources as raw materials. The project can only run in the Java runtime environment.

2, What is a java runtime environment?

If a jar package program wants to compile and run normally, it must be supported by the runtime environment JRE. In fact, the runtime environment is a kind of software designed to run other software. Java provides two environments, one is JDK development environment and the other is JRE running environment. As the runtime environment of Java, JRE includes Java class library, Java class loader and Java virtual machine. JDK is a development kit required by programmers to write Java programs in Java language. It is provided to programmers. JDK includes JRE and javac, a compiler for compiling java source code.   

  • The class loader is responsible for loading classes correctly and connecting them to the core Java class library.
  • The JVM is responsible for ensuring that Java applications have the resources required to run and run well in a device or cloud environment.
  • Java programs can use some basic classes without introducing classes, such as String classes, because alignment is declared and defined in the JRE basic class library.

3, Several links in the construction process

1. Clean up: delete the old class bytecode files previously compiled to prepare for the next compilation.

2. Compilation: compile the java source program into a class bytecode file.

3. Test: automatically call junit program for self-test.

4. Report: displays the results of test program execution.

5. Packaging: package the compiled class bytecode files into war and jar packages.

6. Installation: install your own project to the designated location in maven warehouse before it can be used by other modules.

7. Deployment: put jar and war into production environment for operation.

4, Maven installation and configuration

1. When decompressing the compressed package of Maven program, put it in the directory without Chinese space, and configure Maven after decompressing_ Home or M2_HOME environment variable, pointing to Maven installation directory. At the same time, the path environment variable value is added to point to the bin directory.

2. Maven is written in java language and depends on jre runtime, so java will be checked when starting the program_ Home environment variable. When the computer itself has multiple jdk versions, pay attention to which version the value of the environment variable points to, so as to determine whether the runtime and Maven versions are compatible.

3. Modify the default local warehouse location: edit settings under the conf sub file of the installation directory XML file, modify < localrepository > D: \ repository < / localrepository >.

5, Maven's core concept

1. Agreed directory structure: Maven program development should follow the agreed directory structure. If Maven wants to build automatically, it will go to the agreed directory to find java source files and configuration files to complete the construction. If you do not follow this Convention, you must manually tell Maven the location of these files.

2. pom file: its name means the project object model, which is configured with all construction related parameters. Its expression content is analyzed 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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  
  
 <!--Used in sub modules to specify the pom Details of the parent project. Among them relativePath Give the path of the parent project relative to the child project, so that when constructing the child project, you first start from the phase
 Find the parent item for the path. If not, the parent item will be found from the local library or then the remote library. Subprojects can inherit the
    dependencies,developers,contributors,plugins,reports Other configuration information-->
  <parent>
        <artifactId>sjht-voicemessage</artifactId>
        <groupId>com.sjht.voicemessage</groupId>
        <version>1.0.0</version>
        <relativePath>../pom.xml</relativePath>
  </parent>
  
  
<!--Describes the information of the project, referred to as GAV,When the third party relies on the module, these parameters need to be used to locate the project-->
  <groupId>com.sjht.voicemessage</groupId>
  <artifactId>sjht-voicemessage</artifactId>
  <version>1.0.0</version>
  <name>sjht-voicemessage</name>
  <packaging>pom</packaging>
  <description>xxxx service</description>
  
  
<!--modules Aggregate tag: describes which project modules are included in the project-->
  <modules>
    <module>sjht-voicemessage-entity</module>
    <module>sjht-voicemessage-api</module>
    <module>sjht-voicemessage-biz</module>
    <module>sjht-voicemessage-controller</module>
    <module>sjht-voicemessage-server</module>
  </modules>


<!--Some properties and values are declared, which can be found in this pom Hezi pom Passed in ${Attribute name}Indirectly reference these attribute values-->
  <properties>
    <spring-boot-maven-plugin.version>2.2.6.RELEASE</spring-boot-maven-plugin.version>
    <dockerfile-maven-plugin.version>1.4.12</dockerfile-maven-plugin.version>
    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    <maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>
    <maven-javadoc-plugin.version>3.0.0</maven-javadoc-plugin.version>
    <maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
    <maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
    <seata.version>1.2.0</seata.version>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>


<!--Specify the addresses of private warehouses and central warehouses for maven You can connect to the warehouse through these addresses-->
   <!--In addition to this method, you can also maven Installation directory/conf in settings.xml Configuration under file-->
  <repositories>
    <repository>
      <id>sjht-nexus</id>
      <name>Sjht-Repository</name>
      <url>https://nexus.xxx.com/repository/maven-public/</url>
    </repository>
    <repository>
      <id>aliyun-nexus</id>
      <name>aliyun nexus</name>
      <url>https://maven.aliyun.com/repository/public/</url>
    </repository>
  </repositories>
  
  
<!--Specify the warehouse address of the plug-in so that maven You can use these addresses to connect to the warehouse to download plug-ins(maven All actions of are done by the plug-in)-->
  <pluginRepositories>
    <pluginRepository>
      <id>aliyun-nexus</id>
      <name>aliyun nexus</name>
      <url>https://maven.aliyun.com/repository/public/</url>
    </pluginRepository>
  </pluginRepositories>
 
 
<!--appoint Maven The warehouse address of the distribution built by the distribution, in use mvn deploy Command is used when distributing the generated build to the remote warehouse-->
   <!--  Different versions can specify different distribution warehouses. The distribution needs login authentication and needs to be in the maven Under the installation directory settings.xml Configure the account and password in the file.
         settings.xml in server Under element id The value of must be the same as POM in repository or snapshotRepository lower id The values of are exactly the same -->
   <!-- <servers>    
         <server>    
          <id>nexus-releases</id>    
          <username>admin</username>    
          <password>admin123</password>    
        </server>    
        <server>    
          <id>nexus-snapshots</id>    
          <username>admin</username>    
          <password>admin123</password>    
        </server>      
     </servers>   -->
     
  <distributionManagement>
     <!--appoint Releases Warehouse to distribute stable version-->
    <repository>
      <id>nexus-releases</id>
      <name>Releases</name>
      <url>https://nexus.xxxx.com/repository/maven-releases/</url>
    </repository>
    
    <!--appoint snapshot Warehouse for distribution of development version-->
    <snapshotRepository>
      <id>nexus-snapshots</id>
      <name>Snapshot</name>
      <url>https://nexus.xx.com/repository/maven-snapshots/</url>
    </snapshotRepository>
  </distributionManagement>
 
 
<!--dependencyManagement For parent POM In, when a subproject references a project, it can not specify a version. At this time, it will look up from the superior until
     Find possession dependencyManagement Elemental POM,Then use the version specified under this node-->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>io.seata</groupId>
        <artifactId>seata-spring-boot-starter</artifactId>
        <version>1.2.6</version>
      </dependency>
      <dependency>
        <groupId>com.tencentcloudapi</groupId>
        <artifactId>tencentcloud-sdk-java</artifactId>
        <version>3.1.390</version>
      </dependency>
    </dependencies>
  </dependencyManagement>
   
 
<!--This node is associated with dependencyManagement Nodes differ in:
      1,If by dependencyManagement Including, and its effect is as described above;
      2,If not dependencyManagement If yes, all declarations under this node will be inherited by the child project(Even sub projects pom Dependency is not introduced in);     
    3,dependencyManagement It only declares dependencies, and does not implement the introduction. Therefore, the declarations that need to be displayed in the subproject need to use dependencies. If the dependency is not declared in the child project, it will not be inherited from the parent project; Only when the dependency is written in the child project and no specific version is specified, the item will be inherited from the parent project, and version and scope All read from parent pom;another If the version number is specified in the external project, the version number specified in the sub project will be used jar edition.
--> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> </dependency> </dependencies> <!-- Multi environment profile definition, Profile Allows you to customize a special build for a special environment, a Profile You can override the final name of the project component, project dependencies, and plug-in configuration to affect the construction behavior, Profile You can also override the distribution configuration. maven Provides a method to "activate" one for different environmental parameters profile The way, called profile Activate. profile Activation method: 1,activeByDefault Active by default. 2,use-P Activation of parameter display(for example mvn package –P test Indicates use test Configuration file to build the project). 3,stay settings.xml Used in activeProfiles To specify the to be activated profile,Activated in this way profile Active in all cases. 4,When we use activeByDefault or settings.xml Active is defined in profile,However, when we are doing some operations and don't want it to be activated, we can use it at this time " mvn operation -P !profileid " In the current operation profile Will not be active. --> <profiles> <!-- development environment --> <profile> <id>dev</id> <properties> <profile.active>dev</profile.active> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <!-- testing environment --> <profile> <id>test</id> <properties> <profile.active>test</profile.active> </properties> </profile> <!-- production environment --> <profile> <id>prod</id> <properties> <profile.active>prod</profile.active> </properties> </profile> </profiles> <!-- Project Build,yes<project>Direct child element of,maven Global configuration parameters of the build process: 1,finalName Node: Specifies the name of the built target file 2,directory Node: Specifies the target file storage directory of the build 3,defaultGoal Nodes: executing build When a task is, if no target is specified, the default value of is used. For example, execute on the command line mvn,Is equivalent to execution mvn install
4,filter Nodes: defining*.properties File, defined in filter In file name=value Key value pairs will be displayed in build Era replacement ${name}Apply values to resources Yes. maven Default filter Folder is ${basedir}/src/main/filters. 5,resources Node: used to include or exclude some resource files. 6,resources.resource.directory Nodes: defining resource The folder where the file is located. The default is ${basedir}/src/main/resources. 7,resources.resource.includes Node: specifies which files will be matched to*As a wildcard. 8,resources.resource.excludes Node: specifies which files will be ignored. 9,resources.resource.targetPath Nodes: specifying build Later resource The default folder is basedir. Usually packaged in jar Medium resources The target path for is META-INF. 10,testResources Nodes: defining and resources Nodes are similar, except in test When used. 11,build.plugins Node: used to specify the plug-in used. 1,GAV: Specify the coordinates of the plug-in to use. 2,extensions: Load plugin of extensions,Default to false 3,inherited: true/false,this plugin Apply to this pom My child pom,Default to true 4,configuration: Configure this plugin Expected properties 5,dependencies: As plugin Dependence of 6,executions: plugin There can be multiple targets, and each target can have a separate configuration, which can plugin Bind to different stages 12,build.pluginManagement Node: pluginManagement Configuration and plugins The configuration is the same, only for inheritance, so that it can be used in children pom Used in(son pom Just configure the plug-in groupId,artifactId that will do).
--> <build> <defaultGoal>install</defaultGoal> <finalName>sjht-voicemessage-server</finalName> <directory>${basedir}/target</directory> <filters> <filter>/src/main/filters/dev.properties</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> <targetPath>META-INF/plexus</targetPath> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <targetPath>META-INF/plexus</targetPath> <filtering>true</filtering> </resource> </resources> <testResources> </testResources> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot-maven-plugin.version}</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> </project>

3. Coordinate GAV import dependency: locate the only Maven project in the warehouse using three parameters groupId, artifactId and version. groupId is usually expressed in reverse order of the company's project website, artifact ID is usually expressed as a module, and version is the version number. These coordinates correspond to the path of Maven project in the warehouse.

      <dependency>
        <groupId>com.sjht.starter</groupId>
        <artifactId>sjht-dependencies</artifactId>
        <version>1.0.0</version>
        <exclusions> <!-- Exclude child dependencies jline -->
<exclusion>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
          </exclusion>
        </exclusions>
</dependency>

4. Dependency scope: if one project needs to use another project, dependency is formed between projects. In dependency The dependent ranges (compile, test, runntime, provided, system) can be configured under the scope node. The default value is compile.

compile indicates that the dependent project needs to participate in the compilation of the current project.

Test means that the dependent project is only involved in testing related work, including the compilation and execution of test code.

runntime means that the dependent project does not need to participate in the compilation of the project, but it needs to participate in the later test and run cycle.

provided means that you don't need to package it when packaging, and other facilities (Web Container) will provide it.

System is the same as provided, but the dependent items are not captured from the maven warehouse, but from the local file system. They must be used in conjunction with the systemPath property.

5. Dependency passing: when introducing a dependency into a child pom, when the scope of the dependency is identified as compile, the dependency can be passed up to the parent pom, and the parent can use the dependency without declaring the dependency. (dependent delivery may cause jar conflicts)

6. Dependency exclusion: when two projects depend on jar packages of the same type and different versions, jar packages will conflict. We can use the exclusions tag to manually exclude redundant and unnecessary jar packages when introducing dependencies.

7. Dependency conflict handling principle: maven adopts the principle of shortest path first by default, the principle of overwriting the first declaration in the same pom and the principle of first declaration in different POMS with the same path to choose to use jar packages.

8. Dependent version management:

a. uniformly put the version number in the properties tag and put it into the version tag through ${name}. One modification takes effect in multiple places.

b. by declaring the version in the parent POM, the child POM is managed in a unified way. Note that the parent project is neither jar nor war. The packaging method can only be POM. The parent POM specifies the version number, and the child POM does not need to specify the version when declaring the dependency.

9. Aggregation Engineering: use the modules tag to specify the relative path of sub engineering modules. The so-called aggregation is to divide the project into modules. Aggregation engineering is mainly used to facilitate the project integration of unified management dependency and vertical + horizontal segmentation of the project.

10. Life cycle: several links in the construction process are carried out in sequence. Maven provides three sets of relatively independent life cycles, namely Clean Lifecycle, Default Lifecycle and Site Lifecycle

Clean Lifecycle: do some cleanup before the real build.

Default Lifecycle: the core cycle of construction, including compilation, testing, packaging, installation, deployment, etc.

Site Lifecycle: generates project reports, sites, and publishing sites.

11. Warehouse: the warehouse includes local warehouse (current computer) and remote warehouse (central warehouse and LAN private warehouse). The central warehouse is officially managed by maven, and the private warehouse is usually built by Nexus. When Maven finds dependencies, it will first find and download them from the local warehouse, private warehouse and central warehouse, and synchronize them to the private warehouse and local warehouse. The contents stored in the warehouse usually include Mven's own plug-ins, third-party tool jar packages and Maven projects developed by itself. These contents are managed and used in a unified manner.

6, Common Maven commands

To execute Maven commands related to the build process, you must enter POM Can only be executed in the directory where XML is located. Common commands are:

1. Cleaning: mvn clean

2. Compile the main program: mvn compile

3. Compile test program: MVN test compile

4. Execute test: mvn test

5. Package: mvn package

6. Install to warehouse: mvn install

7. Push maven project to remote warehouse: mvn deploy

The following commands of the above commands will include the previous command (except MVN test compile), and the execution of each command starts from mvn clean. If you want to skip the test phase during packaging or installation, add the parameter - dmaven. After the command test. skip=true . Combined with dockerfile, it can also be packaged into a docker image and pushed to the server. The command is as follows:

8. Package to the docker server (tcp connection to port 2375 is required): mvn dockerfile:build - dmaven test. skip=true

9. Push to the image warehouse (you need to configure the warehouse address and log in to the warehouse): mvn dockerfile:push - dmaven test. skip=true

7, Download the jar package from the official website

Visit Maven central warehouse https://search.maven.org/ perhaps https://mvnrepository.com/ , you can find the jar you need and copy the configuration code to your POM Under the dependencies node in the XML file, reload the Maven project, and the plug-in will automatically download jars to the local warehouse for reference.

8, MAVEN plug in

Maven is essentially just a plug-in framework. Its core does not perform any specific construction tasks. All tasks are completed by plug-ins. Each step of the construction process is responsible for a plug-in. Maven provides two types of plug-ins: Build plugins and Reporting plugins.

Build plugins are executed at build time and are displayed in POM XML is configured in the} element. The Reporting plugins are executed during the website generation process and in POM XML is configured in the} element. The following are common plug-ins:

1. Clean plug-in: clean the target file after construction. Delete the target directory.

2. compiler plug-in: compile Java source files.

3. surefile plug-in: run JUnit unit test. Create a test report.

4. JAR plug-in: build JAR files from the current project.

5. WAR plug-in: build WAR files from the current project.

6. Javadoc plug-in: generate Javadoc for the project.

7. antrun plug-in: a collection of ant tasks run from any stage of the construction process.

These plug-ins are all in POM The plugins element is defined in XML. Each plug-in can have multiple targets, define the use stage of the plug-in, and configure the tasks to be executed by binding to the target of the plug-in. Maven will take care of the rest. It will download plug-ins that are not available in the local repository and start processing. For example:

<build>
<plugins>
   <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-antrun-plugin</artifactId>
   <version>1.1</version>
   <executions>
      <execution>
         <id>id.clean</id>
         <phase>clean</phase>
         <goals>
            <goal>run</goal>
         </goals>
         <configuration>
            <tasks>
               <echo>clean phase</echo>
            </tasks>
         </configuration>
      </execution>     
   </executions>
   </plugin>
</plugins>
</build>