Mind mapping

Maven to build

What is Maven

An accumulation of knowledge, expert, connoisseur. Cross-platform project management tool. Open source project organized by Apache. It mainly serves project construction, dependency management and project information management based on Java platform.

Similar to Linux platform YUM, APT, front-end domain NPM. Maven’s predecessor is Ant. At present, the source code of Tomcat is built and managed by Ant. The more advanced tools are Gradle and Spring project.

What is building

What builds: The process of compiling, running unit tests, generating documentation, packaging, deploying, that’s a build.

Steps to build:

  • Clean the clean: Deletes the old class bytecode file that was compiled previously.
  • Compile the compile: Compiles Java source programs into class bytecode files.
  • Test the test: Automatic test, automatic call junit program.
  • Report the report: Tests the results of program execution.
  • Packaging packageFor the dynamic Web project, use the War package. For the Java project, use the JAR package.
  • Install the install: Copies the packaged files to a specified location in the repository (maven-specific concept).
  • Deploy the deploy: Copy the war package generated by the dynamic Web project to the Servlet container for running.

Project skeleton

Pom: Project Object Model

Root directory: project name | - SRC: source | -- - | -- - the main, the main program | -- - | -- - | - Java: the main program code path | -- - | -- - | -- - the resource: the main program configuration file path | -- - | -- - the test: Test | -- - | -- - | - Java: test code path | -- - | -- - | -- - the resource: test configuration file path | - pom. The XML: maven configuration fileCopy the code

A simple demo

# #1.MVN archetype: generate-darchetypecatalog =internal ##2.Compile the currently generated project MVN compile ##3.Run another command MVN test-compile MVNpackageMVN clean MVN install MVN depolyCopy the code

Coordinates and dependencies

What are coordinates

Analogous to plane geometry in mathematics, coordinates (x, y), any coordinate can uniquely identify a point in the plane.

This point corresponds to the files of.jar,.war, etc.

Maven uses elements such as groupId, artifactId, Version, Packaging, and classifier to compose its own coordinates and define a set of such rules. As long as the correct coordinate element is provided, Maven can find the corresponding component.

Coordinate elements

  • groupId: Defines the actual project to which the current Maven project belongs.
  • artifactId: Defines a Maven project (module) in the actual project.
  • packaging: Defines how Maven projects are packaged. Jar, WAR, POM. The default is JAR.
  • version: Defines the current version of the Maven project.
  • classifier: Distinguish between artifacts with different contents built from the same artifact.

Application Scenario of classifier

Distinguish between packages based on different JDK versions

<dependency>  
    <groupId>net.sf.json-lib</groupId>   
    <artifactId>json-lib</artifactId>   
    <version>2.22.</version> <classifier>jdk13</classifier> <! --<classifier>jdk15</classifier>--> </dependency>Copy the code

Distinguish between the different components of the project

<dependency>  
    <groupId>net.sf.json-lib</groupId>   
    <artifactId>json-lib</artifactId>   
    <version>2.22.</version> <classifier>jdk15-javadoc</classifier> <! --<classifier>jdk15-sources</classifier> --> </dependency>Copy the code

The component name corresponds to the coordinates. The general rule is: artifactId-version[-classifier]. Packaging.

Rely on the statement

<dependencies>
  <dependency>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
    <type></type>
    <optional></optional>
    <exclusions>
      <exclusion>
        <artifactId></artifactId>
        <groupId></groupId>
      </exclusion>
      ...
    </exclusions>
  </dependency>
  ...
</dependencies>
Copy the code
  • groupId,artifactId,version: Base coordinates of dependencies.
  • type: Dependency type, which corresponds to the packaging of the project, is not required.
  • scope: Scope of dependencies, explained later.
  • optional: Indicates whether a dependency is optional.
  • exclusions: Used to exclude transitive dependencies.

Depend on the range

  • Compile: compile-dependent scope

    If not specified, the dependency scope is used by default. This works for compiling, testing, and running all three classpath types. Such as spring – the core.

  • Test: Tests the dependency scope

    This is only valid for test classpath, only for compiling tests and running tests, not for packaging. Such as JUnit.

  • Provided: Dependency scope has been provided

    Valid for compile and test classpath, but not at run time. For example, servlet-API is required for compiling and testing projects, but in the real world, the container is already provided and maven’s repeated references are not required.

  • Runtime: Run-time dependency scope

    Valid for test and running classpath, but not when compiling main code. For example, the JDBC driver implementation package. Specific JDBC drivers are only required to execute tests or run projects.

  • System: system dependency range

    Exactly the same as the Provided dependency scope, but the path to the dependent file must be explicitly specified through the systemPath element when using the scope. Because such dependencies are not resolved through Maven repositories and are often tied to native systems, they should be used with caution, potentially making builds non-portable. The systemPath element can refer to environment variables such as:

    <dependencies>
      <dependency>
        <groupId>javax.sql</groupId>
        <artifactId>jdbc-stdxt</artifactId>
        <version>2.0</version>
        <scope>system</scope>
        <systemPath>${java.home}/lib/rt.jar</systemPath>
      </dependency>
    </dependencies>
    Copy the code
  • Import: Imports the dependency scope

    Effect only in the dependencyManagement tag. Import the content of the defined POM node

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-framework-bom</artifactId>
          <version>4.316..RELEASE</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    Copy the code

Dependency mechanisms and features

Depend on the transfer

  • A->B(compile) : the first direct dependency
  • B->C(compile) : second direct dependency
  • A->C(compile) : transitive dependencies

When configured in A

<dependency>  
    <groupId>com.B</groupId>  
    <artifactId>B</artifactId>  
    <version>1.0</version>  
</dependency>
Copy the code

The C package is automatically imported.

The range of transitive dependencies is shown below:

Rely on mediation

When problems arise with transitive dependencies, it is clear from which dependency path the transitive dependency was introduced.

First, the shortest path first

  • A – > B > C – > X (1.0)
  • A – > D – > X (2.0)

Since only one version of the package can be imported, choose the shortest path to import X(2.0)

Second, the first declarant principle

  • A – > B – > Y (1.0)
  • A – > C – > Y (2.0)

In this case, the first declarator takes precedence because the length of the dependent path is the same. If B dependencies are declared in the POM file before C dependencies, Y(1.0) is introduced, provided the path length is consistent. The following dependencies can be used for testing:

<dependencies>
  <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.41.</version> <exclusions> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion>  </exclusions> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> <exclusions> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion>  </exclusions> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version>
  </dependency>

</dependencies>
Copy the code

One thing to note here is the following dependencies:

<dependencies>
  <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
  </dependency>

  <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
  </dependency>
</dependencies>
Copy the code

By two principles, the expected result should be that builds of version 1.11 will be relied upon. The actual results, however, depend on version 1.10. What! Isn’t this a violation of Maven’s first definition of dependency mediation?

This is a dependency plugin. By default, the dependency plugin uses a copy strategy. When the build declaration is in the same POM and groupid and artifactId are the same, the latest declaration prevails, and the latter overwrites the former.

Note that there is no dependency mediation involved. My understanding is that dependency mediation only occurs when the build is from a different POM, and the build statement is in the same POM, so dependency mediation is not triggered.

Optional dependence

A->B, B->X (optional), B->Y (optional)

Project A depends on project B, and Project B depends on projects X and Y.

In theory, project A will rely on project B, X and Y.

However, X and Y dependencies may be mutually exclusive to B. For example, B is a database isolation package that supports a variety of databases, such as MySQL and Oracle. When building B projects, the two databases need to be supported, but when using this tool package, only one database will be relied on.

In this case, you need to declare X and Y as optional dependencies in the PROJECT B POM file as follows:

<dependency>  
    <groupId>com.X</groupId>  
    <artifactId>X</artifactId>  
    <version>1.0</version>  
    <optionnal>true</optionnal>
</dependency>

<dependency>  
    <groupId>com.Y</groupId>  
    <artifactId>Y</artifactId>  
    <version>1.0</version>  
    <optionnal>true</optionnal>
</dependency>
Copy the code

With the OptionNAL element, only the current item B is affected. When other items depend on item B, neither dependency is passed.

Project A depends on project B, and if the actual application database is X, the X dependency needs to be explicitly declared in A’s POM.

warehouse

Warehouse classification: includes local warehouse and remote warehouse. Among them remote warehouse includes: private server and central warehouse. The order in which the search is built:

  • Local repository
  • Maven Settings Profile repository;
  • Repository as defined in the profile in POM.xml;
  • XML repositorys;
  • Maven Settings mirror;
  • Central c.

The life cycle

Maven’s life cycle is designed to abstract and unify all of the build process, including almost all of the build steps of project cleanup, initialization, compilation, testing, packaging, integration testing, verification, deployment, and site generation.

Maven’s life cycle is abstract and does no real work of its own. The actual tasks are left to the plug-in.

This means that Maven defines the overall structure of the algorithm only in the superclass, which controls the actual behavior by overriding the methods of the superclass (Template Method in design pattern). The pseudocode is as follows:

public abstract class AbstractBuilder {
    public void build() {
        init();
        compile();
        test();
        package(a); integrationTest(); deploy(); } protected abstract void init(); protected abstract void compile(); protected abstract void test(); protected abstract voidpackage(a); protected abstract void integrationTest(); protected abstract void deploy(); }Copy the code

Three life cycles

Maven’s life cycle is not a monolithic one. Maven has three independent life cycles: Clean, Default, and Site.

  • cleanThe purpose of the life cycle is to clean up the project;
  • defaultThe purpose of the life cycle is to build projects;
  • siteThe purpose of the life cycle is to establish the project site;

Single life cycle execution order

Each life cycle contains phases that are sequential, and the later phases depend on the previous phases.

Take the Clean life cycle, which includes the pre-Clean, Clean, and post-Clean phases. When pre-clean is called, only the pre-clean phase is executed;

When clean is called, the pre-clean and clean phases are executed sequentially, and so on.

Relationships between life cycles

The three life cycles themselves are independent, and a user can call just one phase of the Clean life cycle or just one phase of the Default life cycle without having any impact on the other life cycles.

For example, when a user invokes the Clean phase of the Clean lifecycle, no phase of the Default lifecycle is triggered, and vice versa.

Detailed explanation of the stages of the life cycle

clean

Life cycle stage describe
pre-clean Perform some work that needs to be done before cleanup.
clean Clean up the files generated during the last build.
post-clean Perform some work that needs to be done after the cleanup.

default

It consists of 23 phases. Only the key steps are described here, as follows:

Life cycle stage describe
validate Check that the project configuration is correct and that all necessary information is available to complete the build process.
initialize Initialize the build state, such as setting properties.
generate-sources
process-sources Process project resource files, process project master resource files. Typically, the contents of the SRC /main/ Resources directory are copied to the main classpath directory of the project output after variable substitution and so on.
generate-resources
process-resources
compile Compile the main source of the project. Typically, you compile Java files in the SRC /main/ Java directory into the main classpath directory of the project output.
process-classes Handles compile-generated files, such as Java Class bytecode enhancements and optimizations.
generate-test-sources
process-test-sources Process project test resource files. Typically, the contents of the SRC /test/resources directory are copied to the test CLASspath directory in the project output after variable substitution and so on.
test-compile Compile the test code for the project. In general, compile Java files in the SRC /test/ Java directory into the test classpath directory of the project output.
process-test-classes
test Run the tests using an appropriate unit testing framework, such as JUnit.
prepare-package Do whatever is necessary to prepare the packaging before the actual packaging.
package Take the compiled code and package it in a releasable format, such as a JAR, WAR, or EAR file.
pre-integration-test Perform the required actions before the integration test is executed. For example, set the required environment variables.
integration-test Process and deploy the necessary engineering packages to an environment where integration tests can run.
post-integration-test Perform the necessary actions after the integration test has been executed. For example, clean up the environment.
verify Run inspection operations to verify that the project package is valid and meets quality requirements.
install Install the project package to the local repository, which can be used as a dependency of other local projects.
deploy Copy the final project package to a remote repository to share with other developers and projects.

site

Life cycle stage describe
pre-site Perform some work that needs to be done before building the project site.
site Generate project site documentation.
post-site Perform some work that needs to be done after the project site is built.
site-deploy Publish the generated project site to the server.

The plug-in

Maven’s three life cycle phases do not do any real work. The actual work is done by the plug-in, and each life cycle phase is done by the goals of the plug-in. Declare the following in the POM file (packaged source file plug-in) :

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-source-plugin</artifactId>
      <version>2.11.</version>
      <executions>
        <execution>
          <id>attach-sources</id>
          <phase>verify</phase>
          <goals>
              <goal>jar-no-fork</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
Copy the code

Plug-in goals

A plug-in may have multiple functions, and each function is a goal. For example, the Maven-dependency plugin has more than a dozen goals, each with a function.

The plug-ins target dependency: Analyze, Dependency: Tree, and dependency: List.

General notation: The colon is preceded by the plug-in prefix and followed by the target of the plug-in. For example, the compiler: the compile.

Plug-in binding

Built-in binding

Maven has a set of built-in plugin bindings for fast builds. The plug-in bindings for the three life cycles are as follows (which are actually the binding of each life cycle phase to the target of the plug-in).

The construction method of the default life cycle depends on its packaging type, which is specified by packaging in POM. There are two types: JAR and WAR. Here is the default bound plug-in lifecycle diagram:

Custom binding

Custom bindings allow us to control the alignment of the plug-in’s goals and lifecycle. Take the source JAR that generates the project’s main code.

The plugin used and its target are: maven-source-plugin:jar-no-fork. Bind it to the Default life cycle phase verify (you can specify any of the three life cycles).

<build>
  <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>2.11.</version> <executions> <execution> <id>attach-sources</id> <! -- Specify which phase of the life cycle is being used --> <phase>verify</phase> < Goals > <! Executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions, executions.Copy the code

The plug-in configuration

  • Using the command line

    Add the -d parameter to the Maven command, along with a parameter key = parameter value, to configure the plug-in target parameter.

    The maven-surefire-plugin provides a maven.test.skip parameter that will skip tests when true:

    -- Compare MVN install MVN install -- dmaven.test.skip =true
    Copy the code
  • Use POM global configuration

    When you declare a plug-in, you apply a global configuration to the plug-in that all subsequent uses of the plug-in follow. For example, if you specify maven-compile-plugin to compile 1.7 source files:

    <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-compiler-plugin</artifactId>
       <configuration>
           <fork>true</fork>
           <source>1.7</source>
           <target>1.7</target>
       </configuration>
    </plugin>
    Copy the code

Aggregation and inheritance

Aggregation: In order to build more than one project module at a time, you need to aggregate multiple project modules

<modules> <module> <module> <module> <module> <module>Copy the code

Inheritance: To eliminate duplication, extract many of the same configurations, such as dependency, grouptId, version, etc

<parent>  
    <groupId>com.xxxx.maven</groupId>
    <artifactId>parent-project</artifactId>
    <version>0.01.-SNAPSHOT</version> <relativePath>.. /ParentProject/pom.xml</relativePath> </parent>Copy the code

The following elements can be inherited:

  • GroupId, project groupId;
  • Version, project version;
  • Description, project description information;
  • Organazation, the organizational information of the project;
  • InceptionYear, the founding year of the project;
  • Developers;
  • Ficolin-3, contributor information for projects;
  • DistributionManagement, deployment information for the project;
  • IssueManagement, defect tracking system information of the project;
  • Cima Management, Continuous integration system information for projects;
  • SCM, version control system information for the project;
  • MailingLists, mailingLists of items;
  • Properties, custom Maven properties;
  • Dependencies, the dependency configuration of the project;
  • DependencyManagement, project dependencyManagement configuration
  • Repositories, repository configuration for the project
  • Build, including project source directory configuration, output directory configuration, plug-in configuration, plug-in management configuration, etc.
  • Reporting, including the report output directory configuration for the project, and the report plug-in configuration.

Notice the following elements, these are allCannot be inherited:

  • artifactId
  • name
  • prerequisites

The relationship between aggregation and inheritance

  • Both have the same thing in common: the mode of play must be POM
  • In a real project, a POM is both an aggregate POM and a parent POM

DependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement: dependencyManagement

Flexible build

Use attributes, the Resources plugin filter, and Maven’s profile feature for flexible environment switching

attribute

The properties element allows users to customize one or more Maven attributes and then reference them elsewhere in the POM using ${attribute name}, which is useful for eliminating duplication.

1. Built-in attributes

  • ${basedir}Represents the project root directory, which contains the pom.xml file
  • ${version}Equivalent to {pom.version} represents the project version

2. POM attributes

All poM elements can be used with project. For example, ${project.artifactid} corresponds to the < project> element value. Common POM attributes include:

  • ${project.build.sourceDirectory}: The project’s main source directory, SRC /main/ Java/by default.
  • ${project.build.testSourceDirectory}: the project’s test source directory, default/SRC /test/ Java /.
  • ${project.build.directory}: project build output directory, default target/.
  • ${project.build.outputDirectory}: the output directory for compiling the main project code, which defaults to target/classes/.
  • ${project.build.testOutputDirectory}: project test code compile output directory, default is target/testclasses/.
  • ${project.groupId}: groupId of the project.
  • ${project.artifactId}: artifactId for the project.
  • ${project.version}: Version of the project, equivalent to ${version}
  • ${project.build.finalName}: The name of the project package output file, default is${project.artifactId}${project.version}

Custom attributes

Custom Maven properties under elements in poM

<properties>
    <swagger.version>2.22.</swagger.version>
</properties>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
Copy the code

4. Settings property

All Settings in settings. XML are available through Settings. Prefix references are the same as POM attributes.

${settings.localRepository} points to the address of the user’s localRepository

5. Java system properties

All Java system properties can be referenced using Maven properties, such as ${user.home} pointing to the user directory.

You can view all of the Java system properties using the command line MVN help:system

6. Environment variable attributes

All environment variables can be referenced using Maven properties that begin with env. For example, ${env.javA_HOME} refers to the value of the JAVA_HOME environment variable.

You can also view all environment variables using the MVN help:system command line.

7. Parent engineering attributes

Variables in the parent project’s POM are prefixed with {parent.version}

Profile

The Profile feature allows us to define multiple profiles, each with different activation conditions and configuration information, to achieve the effect of using different configuration information for different environments.

Profiles can be declared in the following places:

  • M.ml: The profile declared here is valid only for the current project
  • The profile in user settings.xml:.m2/settings.xml is valid for that user’s Maven project
  • Global settings. XML: conf/settings. XML, valid for all Maven projects on this machine

Example:

<project> ... <profiles> <profile> <id>dev</id> <properties> <active.profile>dev</active.profile> <key1>value1</key1> <key2>value2</key2> </properties> <! -- Default activation configuration --> <activation> <activeByDefault>true</activeByDefault> </activation> <! > <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.24..RELEASE</version> </dependency> <dependencies> <! --> <build> <filters> <filter>.. /profile/test-pre.properties</filter> </filters> </build> </profile> </profiles> ... </project>Copy the code

From: juejin. Im/post / 684490…

Give a [look], is the biggest support for IT elder brotherCopy the code

—— end ——