Maven automated build tool

Maven automated build tool

Chapter I Introduction to Maven

1.1 what can Maven do

1) The automatic construction of the project helps developers to compile, test, package, install and deploy the project code.

2) Manage dependencies (manage the various jar packages used in the project).

Dependency: other resources that need to be used in the project, most commonly jar. For example, the project should use mysql driver. Let's say that the project depends on mysql driver.

1.2 what is maven

Maven is an open source project of apache foundation, which is developed using java syntax. The original meaning of Maven is: expert, expert. The pronunciation is ['me ɪ v( ə) n] Or ['mevn].

maven is an automated build tool for projects. Manage project dependencies.

1.3 concepts in maven

①POM
② Agreed directory structure
③ Coordinates
④ Dependency management
⑤ Warehouse management
⑥ Life cycle
⑦ Plug ins and targets
⑧ Inherit
⑨ Aggregate

1.4 acquisition and installation of Maven tools

Address: http://maven.apache.org/ Download the. zip file from.

Installation:

  1. Determine JAVA_HOME to specify the installation directory of jdk. If there is no JAVA_HOME, you need to create JAVA_HOME in the environment variable of windows, and its value is the installation directory of jdk

  2. Unzip apache-maven-3.3.9-bin.zip and put the unzipped files into a directory.

    The path of the directory should not have Chinese or spaces.

  3. Add the path of bin in maven installation directory to path

  4. Test maven installation. Execute mvn -v on the command line

    C:\Users\NING MEI>mvn -v
    Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)
    Maven home: D:\tools\apache-maven-3.3.9\bin\..
    Java version: 1.8.0_101, vendor: Oracle Corporation
    Java home: C:\Program Files\Java\jdk1.8.0_101\jre
    Default locale: zh_CN, platform encoding: GBK
    OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"
    

Other installation methods of maven:

  1. Determine whether JAVA_HOME is valid

  2. In the environment variable, create a file called M2_HOME (or MAVEN_HOME), whose value is Maven's installation directory

    M2_HOME=D:\tools\apache-maven-3.3.9

  3. In the path environment variable, add% M2_HOME%\bin

  4. Test the installation of maven and execute mvn -v on the command line

    C:\Users\NING MEI>mvn -v
    Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)
    Maven home: D:\tools\apache-maven-3.3.9\bin\..
    Java version: 1.8.0_101, vendor: Oracle Corporation
    Java home: C:\Program Files\Java\jdk1.8.0_101\jre
    Default locale: zh_CN, platform encoding: GBK
    OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos"
    

The second chapter is the core concept of Maven

2.1 agreed directory structure

The maven project uses a directory structure that most people follow. It is called the agreed directory structure.

A maven project is a folder. For example, the project is called Hello

Hello Project folder
    \src
    	\main				It is called the main program directory (the code and configuration files that complete the project functions)
             \java          Source code (package and related class definitions)
    		 \resources	    configuration file
    	\test               Place the test program code (the test code written by the developer)
    		 \java          Test code( junit)
    		 \resources     Configuration files required by the test program
    \pom.xml                maven Configuration file, core file

2.2 POM

POM: Project Object Model. maven treats the project as a model. Operating this model is operating the project.

maven realizes project construction and dependency management through pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<!-- project Is the root tag, followed by the constraint 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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    
  <!-- pom The version of the model is 4.0.0 -->  
  <modelVersion>4.0.0</modelVersion>

  <!-- coordinate -->  
  <groupId>com.bjpowernode</groupId>
  <artifactId>ch01-maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  
  <properties>
     <java.version>1.8</java.version>
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  
</project>

2.3 coordinates

The coordinate components are groupid, artifactid and version.

Coordinate function: the function of determining resources is the unique identification of resources. In maven, each resource is a coordinate. The coordinate value is unique. It is called gav for short

  <groupId>com.bjpowernode</groupId>
  <artifactId>ch01-maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

groupId: Organization name, code. Identification of company, group or unit. This value is often used as the reverse of the company domain name.
         For example: school website www.bjpowernode.com, groupId: com.bjpowernode

         If the project scale is relatively large, the domain name can also be written backwards+Name of large project.
	     For example: www.baidu.com ,  Unmanned vehicle: com.baidu.appollo
artifactId:Project name, if groupId There are items in the. At this time, the current value is the sub item name. The item name is unique.
version: Version, the version number of the project, and the number used. It consists of three digits. For example, the main version number.Minor version number.Minor version number, for example: 5.2.5. 
         Note: there are in the version number-SNAPSHOT, Indicates a snapshot, not a stable version.      
   
packaging Types of project packaging, including jar ,war, ear, pom Wait, the default is jar

gav used in the project:

1. Each maven project needs to have its own gav

2. To manage dependencies, you need to use other jar s and gav as identification.

Address to search for coordinates: https://mvnrepository.com/

2.4 dependency

Dependency: other resources (jar s) to be used in the project.

maven needs to be used to represent dependencies and manage dependencies. Dependencies are used together with gav

In the pom.xml file, you need to use dependencies, dependency, and gav to complete the dependency description.

Format:

<dependencies>
  
    <!-- journal -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    <!-- mysql drive -->
     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.16</version>
    </dependency>

</dependencies> 

maven use gav As an identification, Download dependent from the Internet jar.  Download to your local computer maven Manage these used by the project jar

2.5 warehouse

The warehouse stores things. maven's warehouse stores:

1.Maven's plug-ins are also some jar s, which can complete certain functions.

2. We develop the modules of the project ourselves

3. jar package of third-party framework or tool

Classification of warehouse:

  1. Local warehouse (local warehouse): located on your own computer, it is a directory on disk.

    Local warehouse: the default path is /. m2/repository in the directory of the account you log in to the operating system

    Modify the location of the local warehouse: modify the configuration file of maven tool (maven installation path \ conf\setting.xml)

        <localRepository>D:/openrepository</localRepository>
    
  2. Remote warehouse: a warehouse that needs to be accessed through the Internet

    1) Central warehouse: accessed through the Internet, it serves all Maven projects in the world. It is the most authoritative.

    2) Image of central warehouse: it is set up in different locations. There are several servers in Europe, America, Asia and other continents to share traffic for the central warehouse, so as to reduce the pressure of accessing and downloading the central warehouse

    3) Private server: a server deployed in the LAN environment to serve all Maven projects within the current LAN

Configure warehouse

Modify the conf/settings.xml file

<!--1.to configure server -->
  <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>

<!--2.to configure mirror-->
        <mirror>     
            <id>nexus-releases</id>     
            <mirrorOf>*</mirrorOf>     
            <url>http://192.168.0.50:8081/repository/maven-public/</url>     
        </mirror>    
        <mirror>     
            <id>nexus-snapshots</id>     
            <mirrorOf>*</mirrorOf>     
            <url>http://192.168.0.50:8081/repository/maven-snapshots/</url>     
        </mirror>


   <!-- Domestic remote warehouse: Alibaba cloud image -->
        <mirror>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <mirrorOf>central</mirrorOf>
        </mirror>

<!--3.to configure profile:-->
    <profile>    
      <id>nexus</id>    
      <repositories>    
        <repository>    
          <id>nexus-releases</id>    
          <url>http://nexus-releases</url>    
          <releases><enabled>true</enabled></releases>    
          <snapshots><enabled>true</enabled></snapshots>    
        </repository>    
        <repository>    
          <id>nexus-snapshots</id>    
          <url>http://nexus-snapshots</url>    
          <releases><enabled>true</enabled></releases>    
          <snapshots><enabled>true</enabled></snapshots>    
        </repository>    
      </repositories>    
      <pluginRepositories>    
         <pluginRepository>    
                <id>nexus-releases</id>    
                 <url>http://nexus-releases</url>    
                 <releases><enabled>true</enabled></releases>    
                 <snapshots><enabled>true</enabled></snapshots>    
               </pluginRepository>    
               <pluginRepository>    
                 <id>nexus-snapshots</id>    
                  <url>http://nexus-snapshots</url>    
                <releases><enabled>true</enabled></releases>    
                 <snapshots><enabled>true</enabled></snapshots>    
             </pluginRepository>    
         </pluginRepositories>    
    </profile>  

<!--4.use profile-->
     <activeProfiles>    
      <activeProfile>nexus</activeProfile>    
    </activeProfiles>

maven uses the warehouse: maven automatically uses the warehouse. After the project is started, maven executes the maven command. maven first accesses the local warehouse and obtains the required jar s from the warehouse. If the local warehouse does not exist, it needs to access the private server, central warehouse or image.

2.6 maven life cycle, plug-ins and commands

Maven has three independent life cycles

**Clean Lifecycle does some cleaning work before the real build. * * the Clean Lifecycle consists of three stages:

  • Pre clean performs some work that needs to be done before clean
  • clean removes all files generated by the last build
  • Post clean performs some work that needs to be done immediately after clean

Default Lifecycle is the core part of the build, including compilation, testing, packaging, deployment, and so on.

Life cycle phasedescribe
validateCheck whether the project configuration is correct and whether all necessary information for completing the construction process can be obtained.
initializeInitializes the build state, such as setting properties.
generate-sourcesGenerate any source files that need to be included in the compilation phase.
process-sourcesProcess the source code, for example, filter any value.
generate-resourcesGenerate the resource files to be included in the project package.
process-resourcesCopy and process resource files to the destination directory to prepare for the packaging phase.
compileCompile project source code.
process-classesHandle compiled files, such as Java Class bytecode enhancement and optimization.
generate-test-sourcesGenerate any test source code that needs to be included in the compilation phase.
process-test-sourcesProcess the test source code, for example, filter any values.
test-compileCompile the test source code to the test destination directory.
process-test-classesProcess the files generated after compiling the test code files.
testRun tests using an appropriate unit test framework, such as JUnit.
prepare-packageBefore the actual packaging, do whatever is necessary to prepare the packaging.
packageGet the compiled code and package it in a publishable format, such as JAR, WAR or EAR files.
pre-integration-testPerform the required actions before the integration test is executed. For example, set the required environment variables.
integration-testProcess and deploy the necessary engineering packages into the environment where the integration test can run.
post-integration-testPerform the necessary actions after the integration test is executed. For example, clean up the environment.
verifyRun inspection operations to verify that the work package is effective and meets quality requirements.
installInstall the project package into the local warehouse, which can be used as a dependency of other local projects.
deployCopy the final project package to the remote warehouse for sharing with other developers and projects.

Site Lifecycle generates project reports, sites, and publishes sites.

  • Pre site performs some work that needs to be done before generating site documents
  • Site generates site documents for the project
  • The post site performs some work that needs to be done after the site documentation is generated and is ready for deployment
  • Site deploy deploys the generated site documents to a specific server

Plug in: to complete each stage of the construction project, you need to use maven commands. The function of executing commands is completed through plug-ins. Plug ins are jar s and some classes.

Command: the maven function is executed by commands, such as mvn compile

Command:

1) mvn clean: clean command, which is used to delete previously generated data and delete the target directory.

Plug in: Maven clean plugin

2) mvn compile: compile the command, compile the executed code, and compile the java code in the src/main/java directory into a class file.

At the same time, copy the class file to the target/classes directory. This directory, classes, is the root directory where the class files are stored (also called classpath)

Plug in: Maven compiler plugin is a plug-in for compiling code

Maven resources plugin is a resource plug-in that handles the of files. The function is to copy the files in src/main/resources directory to target/classes directory.

3) MVN test compile: compile the command, compile the source files in the src/test/java directory, and copy the generated classes to the target / test classes directory. At the same time, copy the files in src/test/resources directory to test claim directory

Plug in: Maven compiler plugin is a plug-in for compiling code

Maven resources plugin is a resource plug-in that handles the of files

4) mvn test: the test command is used to execute the program in the test classes directory and test whether the main program code in the src/main/java directory meets the requirements.

Plug in: Maven surefire plugin

5) mvn package: packaging. It is used to put the resource class files and configuration files in the project into a compressed file. The default compressed file is jar type. The web application is of war type, and the extension is jar.

Plug in: Maven jar plugin performs packaging processing. Generate a jar extension file and put it in the target directory. The packaged file contains all generated class es and configuration files in the src/main directory, and has nothing to do with test.

6) mvn install: install the generated packaged files into maven warehouse.

Plug in: Maven install plugin installs the generated jar file to the local repository.

2.7 inheritance and aggregation

<!-- Parent project use modules Reference subprojects and aggregate multiple subprojects -->
<modules>
    <module>project1</module>
    <module>project2</module>
    <module>project3</module>
    ...
</modules>

<!-- Use of subprojects parent Inherit parent project -->
<parent>
    <groupId>it.com.pyg</groupId>
    <artifactId>PYG-Parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</parent>

Dependency transfer in aggregation Engineering

Generally, the dependencies and versions used in the project are defined in the pom of the parent module,
Then, in the pom of the sub module, you can directly import any dependency you need. Without introducing the version number, the dependency will be automatically passed from the parent module to the sub module

2.8 custom configuration plug-in

In the pom.xml file, in the build tag. Setting plug-ins

<!-- Set up content related to the build project -->
<build>
  <plugins>
    <!-- Setting plug-ins -->
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>3.8.1</version>
		<configuration>
			<source>1.8</source> <!-- Specifies the of the compiled code jdk edition -->
			<target>1.8</target> <!-- function java Program used jdk edition-->
		</configuration>
	</plugin>
  </plugins>
</build> 

Chapter III integration of Maven and idea

3.1 integration of maven in idea

There is a maven in idea. We want idea to use Maven installed by itself.

  1. Select File- Settings

2) File - Other Settings


Same as above

3.2 creating a normal java project based on maven

3.3 creating a web project

3.4 importing module s into idea

Chapter IV dependency management

① , dependencies: only one such label can exist in a pom.xml file. Total label used to manage dependencies.

② . dependency: contained in the dependencies tag, there can be countless, and each represents a dependency

③ , groupId,artifactId and version: the basic coordinates of the dependency. For any dependency, the basic coordinates are the most important. Maven can find the required dependency according to the coordinates.

④ . type: the dependent type, corresponding to the packaging defined by the project coordinate. In most cases, this element does not have to be declared, and its default value is jar.

⑤ . scope: the dependent range. The default value is compile. It will be explained in detail later.

⑥ Optional: mark whether the dependency is optional.

⑦ . exclusions: used to exclude transitive dependencies, which will be described in detail later.

<project>     
    <dependencies>
        <dependency>
            <groupId>junit</groupId>     
            <artifactId>junit</artifactId>     
            <version>3.8.1</version>
            <type>...</type>
            <scope>...</scope>
            <optional>...</optional>
            <exclusions>     
                <exclusion>     
                  <groupId>...</groupId>     
                  <artifactId>...</artifactId>     
                </exclusion>
          </exclusions>     
        </dependency>        
      </dependencies>     
</project>

4.1 scope of dependence

Dependency scope: use scope to represent the dependency scope.

Dependency scope means that this dependency (jar and inner classes) works at that stage of project construction.

Dependency scope:

* * compile: * * by default, participate in all phases of the construction project

* * test: * * test, which is used in the test phase. For example, junit will be used when executing mvn test.

* * provided: * * provider. When the project is deployed to the server, it does not need to provide the dependent jar, but the dependent jar package of the server

It is obvious that servlet s and JSPS depend on each other

* * runtime: * * only used at run time, such as JDBC driver, applicable to run and test phases.

* * system: * * similar to provided, you need to explicitly provide a jar containing dependencies. Maven will not find it in the Repository.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-31MBznLl-1637653102823)(D:\doc \ notes \ image\image-20211123145338847.png)]

4.2 dependency conflicts

Shortest path first principle

First declare the priority principle if the path is the same

4.3 dependency exclusion

If we introduce A dependency A in the current project, and A depends on B, Maven will automatically introduce the B that A depends on into the current project, but in some cases, B may be an unstable version or have an adverse impact on the current project. At this time, we can exclude B when introducing A.

exclusions: used to exclude transitive dependencies

4.4 optional dependencies

The Optional tag indicates whether the dependency is Optional. The default value is false. It can be understood that if it is true, it means that the dependency will not be passed on. If it is false, it will be passed on

Chapter V common settings

1) It's about the configuration in properties

<properties>
    <maven.compiler.source>1.8</maven.compiler.source> Source code compilation jdk edition
    <maven.compiler.target>1.8</maven.compiler.target> To run code jdk edition
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> Codes used in project construction to avoid Chinese garbled code
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> Code of the generated report
</properties>
  1. global variable

Define the tag in properties. The tag is a variable, and the text of the tag is the value of the variable.

Use a global variable to represent the version number used by multiple dependencies.

Use steps:

1. In the properties tag, define a tag to specify the value of the version

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <!--Custom variable-->
  <spring.version>5.2.5.RELEASE</spring.version>
  <junit.version>4.11</junit.version>
</properties>
  1. Use global variables, syntax ${variable name}
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.version}</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${spring.version}</version>
</dependency>

3) Using resource plug-ins

Information about the configuration file to be processed. maven processes the configuration file by default

① : maven will copy the files in the src/main/resources directory to the target/classes directory

② : maven only processes. Java files in the src/main/java directory, compiles these java files into classes, and copies them to the target/classes directory. Do not process other files.

<build>
  <!--Resource plug-in
      tell maven hold src/main/java Copy the file with the specified extension in the directory to target/classes In the directory.
  -->
  <resources>
    <resource>
      <directory>src/main/java</directory><!--Directory where-->
      <includes>
      <!--Including the.properties,.xml All files will be scanned-->
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
        <!--  filtering option false Do not enable filters, *.property Has played a role
        The role of filtration -->
      <filtering>false</filtering>
    </resource>
  </resources>
</build>

Tags: Maven

Posted on Tue, 23 Nov 2021 05:23:59 -0500 by maca134