Skills: maven's easy tutorial

preface

maven is the most popular project construction system. If it is java related development, it can be said to be indispensable. Although another module management tool grade is emerging, maven is still commonly used by most companies

  • Maven and Maven's warehouse
  • Maven command and build lifecycle
  • maven project POM Detailed explanation of XML format file
  • How does Maven pass dependency and exclude dependency
  • Aggregation and inheritance of Maven
  • mvn usage instance

Pay attention to the official account and exchange with each other. Search by WeChat: Sneak ahead.

Maven and Maven's warehouse

Maven warehouse is used to store Jar packages managed by Maven. There are two types: local warehouse and central warehouse

  • Local warehouse: Maven's local Jar package warehouse
  • Central warehouse: the remote warehouse officially provided by Maven. Maven central warehouse is a warehouse provided by Maven community, which contains a large number of commonly used warehouses. The central repository contains the vast majority of popular open source Java artifacts
  • Remote warehouse: Maven can't find the dependent files in the central warehouse. It will stop the construction process and output an error message to the console. To avoid this situation, Maven provides the concept of remote warehouse, which is a customized warehouse for developers, including the required code base or jar files used in other projects

Maven command and build lifecycle

stagehandledescribe
validateVerification itemsVerify that the project is correct and that all necessary information is available
compileExecute compilationSource code compilation is completed at this stage
testtestRun tests using an appropriate unit test framework, such as JUnit.
packagepackCreate a JAR/WAR package, as in POM The packages mentioned are defined in XML
verifyinspectCheck the results of integration test to ensure that the quality meets the standard
installinstallInstall packaged items to the local warehouse for use by other projects
deploydeployCopy the final project package to the remote warehouse for sharing with other developers and projects

  • When a phase is called by Maven command, such as mvn compile, all phases before and including the phase will be executed
  • maven also has a clean command to remove all files generated by the last build
  • In the build environment, the mvn clean deploy command is often used to clean up, build and deploy projects to remote warehouses

maven project POM Detailed explanation of XML format file

<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.0http://maven.apache.org/maven-v4_0_0.xsd">     
    <!--Coordinates of the parent project-->    
    <parent>  
        <artifactId/> <!--The component identifier of the inherited parent project-->    
        <groupId/>  <!--Globally unique identifier of the inherited parent project-->      
        <version/>  <!--The version of the inherited parent project-->    
        <!-- Parent item purpose pom.xml Relative path of the file-->    
        <relativePath/>    
    </parent>    
    <!--Declare which project descriptor follows POM Model version. The version of the model itself rarely changes-->       
    <modelVersion>4.0.0</modelVersion>     
    <!--The globally unique identifier of the project, which usually uses a fully qualified package name to distinguish the project from other projects. And the path generated during construction is also generated from this, such as com.ex.app The generated relative path is:/com/ex/app-->     
    <groupId>com.ex.app</groupId>     
    <!-- Identifier of the component, which is associated with group ID Uniquely identify a component together-->     
    <artifactId>erhuowang-maven2</artifactId>     
    <!--The type of component produced by the project, such as jar,war,ear,pom. Plug ins can create their own component types-->     
    <packaging>war</packaging>     
    <!--The current version of the project in the format:Main version.Minor version.Incremental version-Restricted version number-->     
    <version>1.0-SNAPSHOT</version>     
    <!--Name of the project, Maven Generated documents-->     
    <name>erhuo-maven</name>     
    <!--Project home page URL, Maven Generated documents-->     
    <url>http://erhuowang.cn</url>     
    <!-- Detailed description of the project-->     
    <description>A maven project to study maven.</description>     
    <!-- Describes the prerequisites in the project build environment. --> 
    <prerequisites> 
        <!-- Required to build the project or use the plug-in Maven Minimum version of --> 
        <maven></maven> 
    </prerequisites>
------------------------------------------------------------------------------------     
    <!--This element describes all dependencies related to the project. These dependencies constitute each link in the project construction process.-->    
    <dependencies>     
      <dependency>    
        <!--Dependent group ID-->    
        <groupId>org.apache.maven</groupId>     
        <!--Dependent artifact ID-->    
        <artifactId>maven-artifact</artifactId>     
        <!--Dependent version number. stay Maven 2 in, You can also configure the range of version numbers.-->    
        <version>3.8.1</version>     
        <!-- Dependency type. The default type is jar. It usually represents the extension of the dependent file, but there are exceptions. A type can be mapped to another extension or classifier. Types often correspond to the packaging method used, although there are exceptions. Examples of some types: jar,war,ejb-client and test-jar. If set extensions by true,Can be in plugin Define new types in. So the previous examples of types are incomplete.-->    
        <type>jar</type>    
        <classifier></classifier>    
        <!--Dependency range. In the process of project publishing, it helps to decide which components are included. For details, please refer to the dependency mechanism.    
            - compile : Default range for compilation      
            - provided: Similar to compiling, but support your expectations jdk Or provided in containers, similar to classpath      
            - runtime: Required for execution      
            - test:    be used for test Use in task      
            - system: Corresponding elements need to be provided externally. adopt systemPath To get      
            - systemPath: Only for use in the range system. Provide corresponding path      
            - optional:   When the project itself is dependent, mark whether the dependency is passed. Used for continuous dependencies-->     
        <scope>test</scope>       
        <!--When calculating the transfer dependency, list the excluded dependent components from the dependent component list-->    
        <exclusions>    
         <exclusion>     
                <artifactId>spring-core</artifactId>     
                <groupId>org.springframework</groupId>     
            </exclusion>     
        </exclusions>       
        <!--Optional dependencies if you are in the project B Middle handle C If the dependency declaration is optional, you need to B Project (e.g. project) A)Explicit reference pairs in C Dependence on. Optional dependencies block the transitivity of dependencies.-->     
        <optional>true</optional>    
     </dependency>    
    </dependencies>  
----------------------------------------------------------------------------------------------
    <build>    
      <!--This element sets the project source code directory. When building a project, the construction system will compile the source code in the directory. The path is relative to pom.xml Relative path of.-->    
      <sourceDirectory/>    
      <scriptSourceDirectory/> <!--In most cases, the contents of this directory will be copied to the output directory(Because scripts are interpreted, not compiled). -->      
      <testSourceDirectory/>   <!--This element sets the source directory used by the project unit test. The path is relative to pom.xml Relative path of.-->     
      <outputDirectory/>     <!--Compiled application class Directory where files are stored.--> 
      <testOutputDirectory/>  <!--Compiled tests class Directory where files are stored.-->       
      <!--Use a series of build extensions from the project-->    
      <extensions>     
           <extension>   <!--Describes the build extensions used.-->      
            <groupId/>   <!--Build extended groupId-->   
            <artifactId/> <!--Build extended artifactId-->  
            <version/> <!--Build extended version-->       
           </extension>    
      </extensions>    
      <!--When the project has no specified objectives( Maven2 Default value when called phase)-->    
      <defaultGoal/>    
      <!--This element describes the path list of all resources related to the project, such as the property file related to the project. These resources are included in the final packaging file.-->    
      <resources> <!--This element describes all resource paths related to the project or test-->    
          <resource>  <!-- Describes the target path of the resource. The path is relative target/classes catalogue-->    
            <targetPath/>    
            <filtering/> 
            <directory/>   <!--Describes the directory where resources are stored. This path is relative POM route-->   
            <includes/> <!--Contains a list of modes, such as**/*.xml.-->    
            <excludes/> <!--List of excluded modes, for example**/*.xml-->     
            </resource>    
      </resources>    
      <!--This element describes all the resource paths related to the unit test, such as the property files related to the unit test.-->    
      <testResources>    
         <!--This element describes all resource paths related to the test-->    
         <testResource></testResource>    
      </testResources>    
      <targetPath/>
      <filtering/>
      <directory/> <!--The directory where all files generated by the build are stored-->    
          <includes/><excludes/>    
      <directory/> 
      <finalName/> <!--The file name of the generated component. The default value is ${artifactId}-${version}. -->    
      <!--When filtering List of filter property files used when the switch is on-->    
      <filters/>    
      
       <!--List of plug-ins used-->    
      <plugins>    
        <!--See build/pluginManagement/plugins/plugin element-->    
        <plugin> </plugin>    
      </plugins>  
      
      <!--Default plug-in information that can be referenced by subprojects. The plug-in configuration item will not be resolved or bound to the life cycle until it is referenced. Any local configuration of a given plug-in will override the configuration here-->    
      <pluginManagement>  
           <plugins>  
               <!--plugin The element contains the information needed to describe the plug-in.-->    
               <plugin>    
                  <groupId/>   <!--The plug-in is in the warehouse group ID--> 
                  <artifactId/> <!--The plug-in is in the warehouse artifact ID-->  
                  <version/>   
                  <extensions/>    
                  <executions> <!--The configuration of a set of goals is performed during the build lifecycle. Each target may have a different configuration.-->   
                    <execution> <!--execution The element contains the information required for plug-in execution--> 
                      <id/>  <!--The identifier of the execution target, which is used to identify the target in the construction process or match the execution target to be merged in the inheritance process--> 
                      <phase/> <!--The construction life cycle phase of the target is bound. If omitted, the target will be bound to the default phase configured in the source data-->      
                      <goals/>  <!--Configured execution target-->    
                      <inherited/>    <!--Is the configuration propagated to the child POM-->    
                      <configuration/> <!--As DOM Object configuration-->     
                    </execution>    
                  </executions>    
                  <!--Additional dependencies required for the project to introduce plug-ins-->    
                  <dependencies>    
                   <!--See dependencies/dependency element-->    
                   <dependency>    
                    ......    
                   </dependency>    
                  </dependencies>           
                  <!--As DOM Object configuration-->    
                  <configuration/>    
               </plugin>    
           </plugins>    
      </pluginManagement>    
    </build>    
 -----------------------------------------------------------------------------------
    <!--Project build in column profile,If activated, the build process is modified-->    
    <profiles>    
      <!--Activate a build process based on environment parameters or command line parameters-->    
      <profile>    
       <id/>      
       <activation>    
        <!--profile Flag of whether to activate by default-->    
        <activeByDefault/> 
        <jdk/>jdk Version, e.g:1.8</jdk>    
        
        <!--When matching operating system attributes are detected, profile Activated. os Element can define some operating system related attributes.-->
        <!--If Maven A property is detected (its value can be in POM Passed in ${name}Reference), which has the corresponding name
        Value, Profile Will be activated. If the value field is empty, the existing attribute name field is activated profile,
        Otherwise, attribute value fields are matched case sensitive-->    
        <property> 
          <name>mavenVersion</name> <!--activation profile The name of the property-->       
          <!--activation profile The value of the property-->    
          <value>2.0.3</value>    
        </property>    
        <!--Provide a file name to activate by detecting the presence or absence of the file profile. missing Check whether the file exists, and activate if it does not exist -->    
        <file>    
         <!--Activate if the specified file exists profile. -->    
         <exists>/usr/local/workspace/</exists>    
         <!--Activate if the specified file does not exist profile. -->    
         <missing>/usr/local/workspace/</missing>    
        </file>    
       </activation>    
       <!--Information needed to build the project. See build element-->    
       <build>    
            <defaultGoal/>    
            <resources>    
             <resource>    
              <targetPath/><filtering/><directory/><includes/><excludes/>    
             </resource>    
            </resources>    
            <testResources>    
             <testResource>    
              <targetPath/><filtering/><directory/><includes/><excludes/>    
             </testResource>    
            </testResources>    
            <directory/><finalName/><filters/>    
            <pluginManagement>    
             <plugins>    
              <!--See build/pluginManagement/plugins/plugin element-->    
              <plugin>    
               <groupId/><artifactId/><version/><extensions/>    
               <executions>    
                <execution>    
                 <id/><phase/><goals/><inherited/><configuration/>    
                </execution>    
               </executions>    
               <dependencies>    
                <!--See dependencies/dependency element-->    
                <dependency>    
                 ......    
                </dependency>    
               </dependencies>    
               <goals/><inherited/><configuration/>    
              </plugin>    
             </plugins>    
            </pluginManagement>    
            <plugins>    
             <!--See build/pluginManagement/plugins/plugin element-->    
             <plugin>    
              <groupId/><artifactId/><version/><extensions/>    
              <executions>    
               <execution>    
                <id/><phase/><goals/><inherited/><configuration/>    
               </execution>    
              </executions>    
              <dependencies>    
               <!--See dependencies/dependency element-->    
               <dependency>    
                ......    
               </dependency>    
              </dependencies>    
              <goals/><inherited/><configuration/>    
             </plugin>    
            </plugins>    
       </build>    
       <modules/>   
         <!--Subproject relative path-->
         <module></module>
       </modules>          
       <!--Discover the list of dependent and extended remote warehouses.-->    
       <repositories>    
           <!--See repositories/repository element-->    
           <repository>    
             <releases>    
              <enabled/><updatePolicy/><checksumPolicy/>    
             </releases>    
             <snapshots>    
              <enabled/><updatePolicy/><checksumPolicy/>    
             </snapshots>    
             <id/><name/><url/><layout/>    
           </repository>    
       </repositories>    
       <!--Discover a list of remote repositories for plug-ins that are used to build and report-->    
       <pluginRepositories>    
           <!--Contains information about the need to connect to the remote plug-in repository.See repositories/repository element--> 
           <pluginRepository>    
             <releases>    
              <enabled/><updatePolicy/><checksumPolicy/>    
             </releases>    
             <snapshots>    
              <enabled/><updatePolicy/><checksumPolicy/>    
             </snapshots>    
             <id/><name/><url/><layout/>    
           </pluginRepository>    
       </pluginRepositories>    
       <!--This element describes all dependencies related to the project -->    
       <dependencies>    
         <!--See dependencies/dependency element-->    
         <dependency/>   
       </dependencies>    
       <dependencyManagement>  
           <dependencies>    
             <!--See dependencies/dependency element-->    
             <dependency>    
             ......    
             </dependency>    
           </dependencies>    
       </dependencyManagement>    
       <!--See distributionManagement element-->    
       <distributionManagement>    
        ......    
       </distributionManagement>    
       <!--See properties element-->    
       <properties/>    
      </profile>    
    </profiles>    
 ------------------------------------------------------------------------------------     
    <!-- The aggregation module is built as part of the project. Each module element listed is a relative path to the directory of the module --> 
    <modules>
        <!--Subproject relative path-->
        <module></module>
    </modules> 
 ------------------------------------------------------------------------------------ 
    <repositories>  <!--Discover the list of dependent and extended remote warehouses.-->      
     <!--Contains information that needs to be connected to the remote warehouse-->    
     <repository>    
         <releases> <!--How to handle the download of release version in remote warehouse-->    
          <!--true perhaps false Indicates whether the warehouse is opened for downloading certain types of components (release version, snapshot version). -->    
         <enabled/>    
          <!-- The options here are: always(All the time), daily(Default, daily), interval: X(here X Is the time interval in minutes), or never(Never).-->    
          <updatePolicy/>    
          <!--When Maven What to do when verifying the component verification file fails: ignore(Ignore), fail(Failure), or warn(Warning).-->   
          <checksumPolicy/>    
         </releases>    
         <!-- How to handle the download of snapshot version in remote warehouse. Yes releases and snapshots These two sets of configurations, POM You can adopt different strategies for each type of component in each separate warehouse-->    
         <snapshots>    
          <enabled/><updatePolicy/><checksumPolicy/>    
         </snapshots>    
         <!--Unique identifier of the remote warehouse. Can be used to match in settings.xml Remote warehouse configured in file-->    
         <id>banseon-repository-proxy</id>     
         <!--Remote warehouse name-->    
         <name>banseon-repository-proxy</name>     
         <!--Remote warehouse URL,Press protocol://hostname/path form -- >    
         <url>http://192.168.1.169:9999/repository/</url>  
         <layout>default</layout>               
     </repository>     
    </repositories>    
------------------------------------------------------------------------------------
    <!--Discover a list of remote repositories for plug-ins that are used to build and report-->    
    <pluginRepositories>    
     <!--Contains information about the need to connect to the remote plug-in repository.See repositories/repository element-->    
     <pluginRepository>    
      ......    
     </pluginRepository>    
    </pluginRepositories>        
------------------------------------------------------------------------------------
    <!-- Default dependency information inherited from all subprojects of the project. This part of the dependency information will not be resolved immediately,But when the subproject declares a dependency (must be described) group ID and artifact ID Information), if group ID and artifact ID If some information other than is not described, it can be passed group ID and artifact ID Match the dependencies here and use the dependency information here.-->    
    <dependencyManagement>    
      <dependencies>    
       <!--See dependencies/dependency element-->    
       <dependency>    
        ......    
       </dependency>    
      </dependencies>    
    </dependencyManagement>       
---------------------------------------------------------------------------------------------  
    <!--Project distribution information, during implementation mvn deploy After indicates the location to publish. With this information, you can deploy the website to a remote server or components to a remote warehouse.-->     
    <distributionManagement>    
        <!--The information required to deploy the components generated by the project to the remote warehouse-->    
        <repository>    
         <!--Is a unique version number assigned to the snapshot-->    
         <uniqueVersion/>    
         <id>banseon-maven2</id>     
         <name>banseon maven2</name>     
         <url>file://${basedir}/target/deploy</url>     
         <layout/>    
        </repository>   
        <!--Information needed to deploy the project's Web site-->     
        <site>    
         <!--Unique identifier of the deployment location to match the site and location settings.xml Configuration in file-->     
            <id>banseon-site</id>     
            <!--The name of the deployment location-->    
            <name>business api website</name>     
            <!--Deployment location URL,Press protocol://hostname/path form -- >    
            <url>     
                scp://svn.baidu.com/banseon:/var/www/localhost/banseon-web      
            </url>     
        </site>    
        <!-- The status of the component in the remote warehouse is given. This element must not be set in a local project because it is automatically updated by the tool. Valid values are: none(Default), converted(Warehouse keeper from Maven 1 POM Switch over), partner(Directly from partner Maven 2 Warehouse synchronization), deployed(from Maven 2 Instance deployment), verified(Correct and final when verified).-->    
       <status/>           
    </distributionManagement>  
---------------------------------------------------------------------------------------------- 
    <!--Replace the name with a value, Properties Can be in the whole POM It can also be used as a trigger condition (see settings.xml In the configuration file activation Description of the element). Format is<name>value</name>. -->    
    <properties/>    
</project>    

How does Maven pass dependency and exclude dependency

  • Transitive dependency: if our project references a Jar package and the Jar package references other Jar packages, Maven will download both directly referenced and succinctly referenced Jar packages to the local by default when the project is compiled
  • Exclude dependencies: if we only want to download the Jar package directly referenced, we need to download it in POM Do the following configuration in XML
<exclusions>
    <exclusion>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
    </exclusion>
</exclusions>
  • Dependency conflict: if multiple jars in the project reference the same Jar at the same time, dependency conflict will occur, but Maven adopts two strategies to avoid conflict, so there is no dependency conflict in Maven
    • Short circuit is preferred, such as A.jar - > b.jar - > X.jar; C.jar - > X.jar, the short path X.jar is preferred
    • Declaration of priority; If the reference path length is the same, in POM Who is declared first in XML

Aggregation and inheritance of Maven

  • Configuring multiple running items at the same time is called aggregation. The aggregated item has a parent class POM XML file, and each project also has its own POM xml
  • When aggregating multiple projects, if the same jars need to be introduced into these aggregated projects, these jars can be written to the parent pom In XML, each sub item can inherit the pom
  • Parent POM xml
<!-- Aggregate multiple items  -->
<modules>
    <module>../modular A</module>
    <module>../modular B</module>
    <module>../modular C</module>
</modules>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.2</version>
        </dependency> 
    </dependencies>
</dependencyManagement>
  • Sub POM XML configuration
<!-- Inherited from the parent class org.apache.shiro jar  -->
<parent>
    <groupId>father pom Of the project groupId</groupId>
    <artifactId>father pom Of the project artifactId</artifactId>
    <version>father pom Version number of the project</version>
</parent>

mvn usage instance

//Create Maven's normal java project
mvn archetype:create -DgroupId=packageName -DartifactId=projectName
//Compile source code
mvn compile 
//Only test without compilation, and do not test compilation
mvn test -skipping compile -skipping test-compile 
//Run test
mvn test 
//Clear generated items
mvn clean
//Install jar s in the local Repository
mvn install
//Clean up the old project and generate a new jar
mvn clean install
//Clear the old project, generate a new jar and upload it to the remote warehouse
mvn clean install deploy

Welcome refers to the error in the text

Reference articles

Keywords: Java Maven Programmer

Added by aprieto on Sun, 30 Jan 2022 07:12:34 +0200