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.

Assuming we don’t have Maven today, compiling, running single tests, packaging, and so on are all separate steps that must be put together manually. With Maven, what we need to do is to use Maven to configure the project, and then enter a simple command (MVN clean, MVN Package, etc. Or directly click the button), so that the application can be built like an automatic pipeline, all the tedious steps can be completed.

Maven is a great build tool, but not just a build tool:

  • Manage tripartite libraries: provide coordinate systems to import dependencies (input coordinates automatically download dependencies), and automatically solve complex dependency problems (version inconsistency, version conflict, dependency bloated, etc.), and provide free dependency central repository for all developers.
  • Manage project information that is otherwise scattered, including project descriptions, developers, licenses, and so on.
  • Plug-in mechanism. Developers can customize plug-ins to fulfill complex build requirements.

At this point, you should have an idea of Maven. Here’s how to use Maven.

Project skeleton

To build projects using Maven, you must follow some Maven conventions. Here is a standard Maven 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

MVN archetype: generate-darchetypecatalog =internal ## 2 MVN test-compile MVN package MVN clean MVN install MVN depoly MVN package MVN clean MVN install MVN depolyCopy the code
  • Build slowly: blog.csdn.net/codercaicai…
  • MVN install command combined with the action situation, to demonstrate

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: Distinguishes 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.2.2</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.2.2</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: indicates the dependency type, corresponding to the packaging of the project. This parameter is not required.
  • Scope: the scope of the dependency.
  • Optional: Indicates whether the tag 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.3.16. 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 dependency B->C(compile) : the second dependency A->C(compile) : transitive dependency

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.

  1. 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)

  1. The first person to declare priority
  • 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.4.1</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? The net friend of similar questions: stackoverflow.com/questions/4… .

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.

Reference: maven.apache.org/plugins/mav…

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> </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

The place where the artifacts (dependencies) are stored is called a repository for unified management.

Assuming that there are now many projects that reference spring-core dependencies, it is not necessary to put a copy of that dependency file in every project folder. Maven’s approach is unified management. A real Maven project does not need to store dependency files. It only needs to declare the coordinates of these dependencies, and Maven automatically finds the components in the repository and uses them when needed.

In order to achieve reuse, for example, at this time you have a packaged JAR (such as converged pay bank SDK package), you can also install or deploy it to the repository and share it with other projects.

The warehouse is divided into local warehouse and remote warehouse. Among them remote warehouse includes: private server and central warehouse.

Maven searches the build order when a dependency is declared:

  1. Local repository
  2. Maven Settings Profile repository;
  3. Repository as defined in the profile in POM.xml;
  4. XML repositorys;
  5. Maven Settings mirror;
  6. Central c.

Life cycle and plug-ins

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(a) {
        init();
        compile();
        test();
        package(a); integrationTest(); deploy(); }protected abstract void init(a);
    protected abstract void compile(a);
    protected abstract void test(a);
    protected abstract void package(a);
    protected abstract void integrationTest(a);
    protected abstract void deploy(a);
}
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.

  • The purpose of the clean lifecycle is to clean up projects;
  • The purpose of the default life cycle is to build projects;
  • The purpose of the site lifecycle is to create project sites;

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.

Note: The general packaging command is clean package XXXXX, clean before package, because clean and package are in two different life cycles.

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.1.1</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.1.1</version>
            <executions>
                <execution>
                    <id>attach-sources</id> 
                    <phase>verify</phase> <! -- Specify which phase of the life cycle is used -->
                    <goals>
                        <goal>jar-no-fork</goal> <! -- Specify which targets to execute the binding plug-in -->
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
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:

MVN install -- dmaven.test. skip=trueCopy 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
  • Getting plug-in information

The official website

Maven.apache.org/plugins/ind… Maven.apache.org/plugins-arc…

Command line fetch

  • Use maven-help-plugin
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-compiler-plugin

mvn help:describe -Dplugin=compiler

mvn help:describe -Dplugin=compiler -Dgoal=compile

mvn help:describe -Dplugin=compiler -Ddetail
Copy the code
  • Use the plug-in’s built-in Help target
mvn compiler:help -Ddetail=true -Dgoal=compile
Copy the code
  • Plug-in prefix

Maven-plugin or maven-prefix− maven-plugin or maven-prefix− maven-plugin or maven-prefix− {prefix}-plugin This can be called directly with MVN prefix:goal.

How to check the plugin prefix: ${MAVEN_HOME}\org\apache\maven\plugins\maven-metadata-central.xml

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>A module</module>
    <module>Module 2</module>
    <module>Module 3</module>
</modules>
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.0.1 - the 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.

Note the following elements, which are not inherited.

  • artifactId
  • name
  • prerequisites

The relationship between aggregation and inheritance:

  • All types 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 (Team members have stepped in holes here.)

Flexible build

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

attribute

Maven.apache.org/pom.html#Pr…

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}Is equivalent to${project.version}or${pom.version}Represents the project version

2. The POM properties

All poM elements can be used with project. For example, ${project.artifactId} corresponds to the < project>

element. Common POM attributes include:

The ${project. Build. SourceDirectory} : main source directory of the project, the default for the SRC/main/Java /. ${project. Build. TestSourceDirectory} : Test source directory of the project, the default is/SRC/test/Java /. ${project. Build. Directory} : project build output directory, default to target /. ${project. Build. OutputDirectory} : Project main code compiler output directory, default to target/classes /. ${project. Build. TestOutputDirectory} : GroupId}: groupId. ${project.artifactid}: Artifactid. ${project.version} : the version of the project, equivalent to ${version} ${project.build.finalName} : The name of the project package output file, which defaults to ${project.artifactid}${project.version}

3. Customize attributes

Custom Maven properties under the element in poM

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

4. Settings properties

All Settings in settings. XML are available via settings. XML. 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 project attributes

Variables in the parent project’s POM are referenced with the prefix ${project.parent}. Parent project versions can also be referenced like this: ${parent. Version}

Note: How to read the external property file? Properties Maven Plugin, github.com/mojohaus/pr…

fileter

Maven’s Properties Filter feature automatically replaces variables wrapped in ${} in configuration files. To make it easier to build different environments, we typically configure different configurations in the POM as properties. By default, Maven properties are resolved only in the POM. Resource filtering means that Maven properties can be parsed in resource files (SRC /main/resources, SRC /test/resources). Enable resource filtering:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
Copy the code

Profile

The Profile feature allows us to define multiple profiles, each with different activation conditions and configuration information, so that different environments can use different configuration information. It can be declared in the following places:

  1. Pom.xml: The profile declared here is only valid for the current project
  2. The profile in user settings.xml:.m2/settings.xml is valid for that user’s Maven project
  3. 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>

        <! -- Activate configuration by default -->
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <! -- Dependencies introduced under this profile -->
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>3.2.4. The RELEASE</version>
            </dependency>
        <dependencies>
        <! -- Variable files that will be loaded under this profile -->
        <build>
            <filters>
                <filter>../profile/test-pre.properties</filter>
            </filters>
        </build>
            
      </profile>
    </profiles>.</project>
Copy the code

A valid label in a profile

> <repositories>  
> <pluginRepositories>  
> <dependencies>  
> <plugins>  
> <properties> (not actually available in the main POM, but used behind the scenes)  
> <modules>  
> <reporting>  
> <dependencyManagement>  
> <distributionManagement>  
> a subset of the <build> element, which consists of:  
    > <defaultGoal>  
    > <resources>  
    > <testResources>  
    > <finalName>  
Copy the code

Advanced features

  • Use SNAPSHOT to manage unpublished artifacts

When using SNAPSHOT to manage artifact versions, the latest dependencies on the remote repository are retrieved each time. Application Scenario Description:

  • Packages that do not need to be published to remote repositories, such as a service provider, an implementation.
  • Packages that need to be published to remote repositories, but progress is still under development and subject to change

Add “-snapshot” after version to automatically deploy to the directory corresponding to SNAPSHOT in the remote repository.

  • Tailor reactor, polymerize item package specify individual module package

Application scenario description of tailored reactor: AN aggregation project contains three main applications (such as gateway service, service provider and helper project), which are roughly structured as follows:

-- Project home directory ------ Gateway project (runnable) ------ Provider project (runnable) ------ Assist project (runnable) ------ API project (dependent) ------ Common project (dependent) ------ pom.xmlCopy the code

When the MVN package is executed in the home directory, the gateway, provider and Assist projects will be packaged. At this time, if the three projects need to be isolated, the clipping reactor will be used. To package the Provider project separately, use the following command:

mvn package -pl provider -am
Copy the code

To package gateway and Assist at the same time, run the following command:

mvn package -pl gateway,assist -am
Copy the code

Reactor details mVN-H:

-am –also-make Builds dependencies of the listed modules at the same time; – AMD-also -make-dependents builds a module that depends on the listed module; -pl — Modules specified by projects construction, separated by commas; – rf-resume-from Restores the reactor from the specified module.

Practical plug-in

  • Use the Versions plug-in to batch change the version number of the parent POM

- https://blog.csdn.net/GGBomb2/article/details/78316068 - set the version number in the top pom directory. - Note: in Windows Powershell 1.1.3-RELEASE should be quoted. CMD do not add MVN versions: set-dnewVersion =1.1.3 -release MVN versions:revert MVN versions:revert MVN versions versions:commitCopy the code
  • Analyze dependencies within a project using the Dependency plug-in

mvn dependency:analyze

#Just look at the branches in the dependency tree that contain the groupId as javax.serlet
mvn dependency:tree -Dincludes=javax.servlet
#Do not want to see a dependency tree that contains a branch whose groupId is javax.serlet
mvn dependency:tree -Dexcludes=javax.servlet
Copy the code

The parameter pattern is defined as follows :[groupId]:[artifactId]:[type]:[version]

The * wildcard is supported for each part (the part separated by the colon). If you want to specify more than one format, you can use the, split, as in:

mvn dependency:tree -Dincludes=javax.servlet,org.apache.*
Copy the code
  • Use the Deploy plug-in to publish multi-module projects differently (some need to be published, some don’t)

<properties>
    <maven.deploy.skip>true</maven.deploy.skip>
</properties>
Copy the code
  • Use the Shade plugin to merge configuration files and so on

My.oschina.net/u/2377110/b…

  • Use the Assembly plug-in to do the output of the aggregate project

My.oschina.net/u/2377110/b…

Project inspired

  1. From the design of Maven plug-in, it reflects the design idea of template method. Can it be used in our project?

cheat

  • Packaging statement
mvn clean install -Ptest -Dmaven.test.skip=true  -X -DskipTests package
Copy the code
  • Setting file

      

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

    <! -- localRepository Default: ~/.m2/repository -->
    <localRepository>Local Maven repository address</localRepository>

    <pluginGroups>
        <pluginGroup>org.codehaus.cargo</pluginGroup>
        <pluginGroup>org.apache.maven.plugins</pluginGroup>
        <pluginGroup>org.codehaus.mojo</pluginGroup>
    </pluginGroups>

    <proxies>
    </proxies>

    <! --> < span style = "max-width: 100%; clear: both; min-height: 1em;
    <! --<servers> <server> <id>xxx_release</id> <username></username> <password></password> </server> <server> <id>xxx_snapshots</id> <username></username> <password></password> </server> </servers>-->
        
    <! -- Set private server to open this configuration -->
    <! -- <profiles> <profile> < ID >nexus</ ID > <repository> < ID > Repository ID </ ID > < URL > Private server address </ URL > <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>warn</checksumPolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>warn</checksumPolicy> </snapshots> </repository> </ pluginRepository> <id> Repository ID </ ID > <url> Private server address </ URL > <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>warn</checksumPolicy> </releases>  <snapshots> <enabled>false</enabled> <updatePolicy>always</updatePolicy> <checksumPolicy>warn</checksumPolicy> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> <activeProfiles> <activeProfile>nexus</activeProfile> </activeProfiles> -->

    <! -- Use Maven mirror repository on Alicloud -->
    <mirrors>
        <mirror>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <mirrorOf>central</mirrorOf>
        </mirror>
    </mirrors>
</settings>
Copy the code

Problems encountered

  • The project path under IDEA contains Chinese compilation failure console garbled characters

Blog.csdn.net/qq_28862535…

  • The Springboot project profile placeholder does not take effect

Stackoverflow.com/questions/3…

References:

  • maven.apache.org/
  • Wiki.jikexueyuan.com/project/mav…