Maven 2022 --- ② POM deepening and strengthening

1, Rethinking Maven (project management function)

1. Maven's full functionality
   at the beginning, we introduced Maven as a tool for "build management" and "dependency management". But in fact, this is only part of Maven's function. Maven's own product positioning is a "project management tool".

2. Concrete embodiment of project management function
  below is the POM file of spring boot starter. You can see that in addition to the familiar coordinate tags and dependencies tags, there are also tags describing project information such as description, url, organization, licenses, developers, scm and issueManagement.

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <!-- This module was also published with a richer model, Gradle metadata,  -->
  <!-- which should be used instead. Do not delete the following line which  -->
  <!-- is to indicate to Gradle or any Gradle module metadata file consumer  -->
  <!-- that they should prefer consuming it instead. -->
  <!-- do_not_remove: published-with-gradle-metadata -->
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.5.6</version>
  
  <name>spring-boot-starter</name>
  <!--Right now jar Introduction to package-->
  <description>Core starter, including auto-configuration support, logging and YAML</description>
  <!--jar Address corresponding to the packet-->
  <url>https://spring.io/projects/spring-boot</url>
  <!--Introduction to organization information-->
  <organization>
    <name>Pivotal Software, Inc.</name>
    <url>https://spring.io</url>
  </organization>
  <!--Licensing information-->
  <licenses>
    <license>
      <name>Apache License, Version 2.0</name>
      <url>https://www.apache.org/licenses/LICENSE-2.0</url>
    </license>
  </licenses>
  <!--Developer-->
  <developers>
    <developer>
      <name>Pivotal</name>
      <email>info@pivotal.io</email>
      <organization>Pivotal Software, Inc.</organization>
      <organizationUrl>https://www.spring.io</organizationUrl>
    </developer>
  </developers>
  <!--jar Package configuration management-->
  <scm>
    <connection>scm:git:git://github.com/spring-projects/spring-boot.git</connection>
    <developerConnection>scm:git:ssh://git@github.com/spring-projects/spring-boot.git</developerConnection>
    <url>https://github.com/spring-projects/spring-boot</url>
  </scm>
  <!--permit-->
  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/spring-projects/spring-boot/issues</url>
  </issueManagement>

  <!--rely on-->
  <dependencies>
    <dependency>
      ......
    </dependency>
  </dependencies>
</project>

Therefore, from the perspective of "project management", Maven provides the following functions:

  • Project object model (POM): the whole project itself is abstracted and encapsulated as an object in the application for management and operation.

  • Global build logic reuse: after Maven encapsulates the whole build process, programmers only need to specify configuration information to complete the build. Upgrade the build process from Ant's "programming" to Maven's "declarative".

  • Standard collection of components: within the standard framework system provided by Maven, all components can be generated and used according to unified specifications.

  • Component relationship definition: Maven defines three basic relationships between components, so that large application systems can use Maven for management

    • Inheritance relationship: through the inheritance relationship from top to bottom, the repeated information in each child component is extracted into the parent component for unified management
    • Aggregation relationship: aggregate multiple components into a whole for unified operation
    • Dependency: Maven defines a series of specifications and standards such as dependency scope, dependency transmission, dependency exclusion and version arbitration mechanism, so that large projects can accommodate hundreds or even more dependencies in an orderly manner
  • Plug in target system: Maven core program defines the abstract life cycle, and then binds the plug-in target to a specific stage in the life cycle, realizing the decoupling of standard and specific implementation, making Maven program highly extensible

  • Maintenance of project description information: we can not only declare the project description information in POM, but also collect the relevant information of the whole project to generate a directly accessible site composed of HTML pages. These project descriptions include:

    • Company or organization information
    • project license
    • Development member information
    • issue management information
    • SCM information

2, Four levels of POM

1. Super POM

  Maven has many default settings during the construction process. For example, the directory in which the source files are stored, the directory in which the test source files are stored, the directory in which the build output is stored, and so on. But in fact, these elements are also defined by Maven. The defined location is: Super POM.

About super POM, Maven's official website introduces it as follows:

The Super POM is Maven's default POM. All POMs extend the Super POM unless explicitly set, meaning the configuration specified in the Super POM is inherited by the POMs you created for your projects.


Super POM is Maven's default POM. Unless explicitly set, all POMS extend the super POM, which means that the configuration specified in the super POM is inherited by the POM you created for the project.

  therefore, even if our own POM does not explicitly specify a parent project (parent POM), it actually inherits the super POM by default. It's like a Java class inherits the Object class by default.

So what is defined in the super POM?

<project>
  <modelVersion>4.0.0</modelVersion>
  <!--Default warehouse address-->
  <repositories>
    <repository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>
  <!--Plug in default warehouse address-->
  <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
    </pluginRepository>
  </pluginRepositories>
 
  <!--structure-->
  <build>
  	<!--Build output directory-->
    <directory>${project.basedir}/target</directory>
    <!--Compile output directory-->
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <!--Final name-->
    <finalName>${project.artifactId}-${project.version}</finalName>
    <!--Test output directory-->
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <!--Source file directory-->
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <!---->
    <scriptSourceDirectory>${project.basedir}/src/main/scripts</scriptSourceDirectory>
    <!--Test directory file-->
    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
    <!--Resource directory-->
    <resources>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>${project.basedir}/src/test/resources</directory>
      </testResource>
    </testResources>
    <!--Plug in management-->
    <pluginManagement>
      <!-- NOTE: These plugins will be removed from future versions of the super POM -->
      <!-- They are kept for the moment as they are very unlikely to conflict with lifecycle mappings (MNG-4453) -->
      <plugins>
        <plugin>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.3</version>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>2.2-beta-5</version>
        </plugin>
        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.8</version>
        </plugin>
        <plugin>
          <artifactId>maven-release-plugin</artifactId>
          <version>2.5.3</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
 
  <reporting>
    <outputDirectory>${project.build.directory}/site</outputDirectory>
  </reporting>
  <!--profile-->
  <profiles>
    <!-- NOTE: The release profile will be removed from future versions of the super POM -->
    <profile>
      <id>release-profile</id>
 
      <activation>
        <property>
          <name>performRelease</name>
          <value>true</value>
        </property>
      </activation>
 
      <build>
        <plugins>
          <plugin>
            <inherited>true</inherited>
            <artifactId>maven-source-plugin</artifactId>
            <executions>
              <execution>
                <id>attach-sources</id>
                <goals>
                  <goal>jar-no-fork</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <inherited>true</inherited>
            <artifactId>maven-javadoc-plugin</artifactId>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <inherited>true</inherited>
            <artifactId>maven-deploy-plugin</artifactId>
            <configuration>
              <updateReleaseInfo>true</updateReleaseInfo>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
 
</project>

2. Parent POM

Like Java classes, POMS are also single inheritance. If we assign a parent POM to a POM, the inheritance relationship is shown in the following figure:

3. Effective POM

① Concept
   effective POM is translated into effective POM in English. Its concept is as follows: in the inheritance relationship of POM, the child POM can override the configuration in the parent POM; If the child POM is not overwritten, the configuration in the parent POM will be inherited. According to this rule, all POMS in the inheritance relationship are superimposed together to get a finally effective POM. Obviously, during the actual operation of Maven, the build operation is executed according to the POM that finally takes effect. The final effective POM is the effective POM, which is called effective POM in English.

② View valid POM S

mvn help:effective-pom

D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration>mvn help:effective-pom [INFO] Scanning for projects... [INFO] [INFO] -----------------< org.example:pro34-ssm-integration >------------------ [INFO] Building pro34-ssm-integration 1.0-SNAPSHOT [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ pro34-ssm-integration --- [INFO] Effective POMs, after inheritance, interpolation, and profiles are applied:

<?xml version="1.0" encoding="GBK"?> 4.0.0 org.example atguigu-maven-210422-new 1.0-SNAPSHOT org.example pro34-ssm-integration 1.0-SNAPSHOT war 1.8 1.8 1.8 org.springframework spring-webmvc 5.3.1 compile org.springframework spring-orm 5.3.1 compile ch.qos.logback logback-classic 1.2.3 compile javax.servlet javax.servlet-api 3.1.0 provided org.thymeleaf thymeleaf-spring5 3.0.12.RELEASE compile org.mybatis mybatis-spring 2.0.6 compile org.mybatis mybatis 3.5.7 compile com.github.pagehelper pagehelper 5.2.0 compile mysql mysql-connector-java 5.1.3 compile com.alibaba druid 1.0.31 compile org.junit.jupiter junit-jupiter-api 5.7.0 test org.springframework spring-test 5.3.1 compile false central Central Repository https://repo.maven.apache.org/maven2 never false central Central Repository https://repo.maven.apache.org/maven2 D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\src\main\java D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\src\main\scripts D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\src\test\java D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\classes D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\test-classes D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\src\main\resources D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\src\test\resources D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target pro34-ssm-integration-1.0-SNAPSHOT maven-antrun-plugin 1.3 maven-assembly-plugin 2.2-beta-5 maven-dependency-plugin 2.8 maven-release-plugin 2.5.3 maven-clean-plugin 2.5 default-clean clean clean maven-resources-plugin 2.6 default-testResources process-test-resources testResources default-resources process-resources resources maven-war-plugin 2.2 default-war package war maven-compiler-plugin 3.1 default-compile compile compile default-testCompile test-compile testCompile maven-surefire-plugin 2.12.4 default-test test test maven-install-plugin 2.4 default-install install install maven-deploy-plugin 2.7 default-deploy deploy deploy maven-site-plugin 3.3 default-site site site D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\site org.apache.maven.plugins maven-project-info-reports-plugin default-deploy site-deploy deploy D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\site org.apache.maven.plugins maven-project-info-reports-plugin D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\site org.apache.maven.plugins maven-project-info-reports-plugin D:\idea2019workspace\atguigu-maven-210422-new\pro34-ssm-integration\target\site
[INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.802 s [INFO] Finished at: 2021-12-13T16:51:49+08:00 [INFO] ------------------------------------------------------------------------

4. Summary

To sum up, the POM we usually use and configure consists of four levels:

  • Super POM: all POMS inherit by default, but there are direct and indirect.
  • Parent POM: this layer may not have one or many layers.
  • Current POM POM configured with XML: the layer we pay most attention to and use most.
  • Effective POM: an implied layer, but actually a layer that really works.

3, Declaration and reference of attributes

1. Various targets of the help plug-in

Official website description address: https://maven.apache.org/plugins/maven-help-plugin

targetexplain
help:active-profilesLists the currently activated profile s
help:all-profilesList all available profile s of the current project
help:describeDescribes the properties of a plug-in and / or Mojo
help:effective-pomDisplay valid POM S in XML format
help:effective-settingsDisplay the calculated settings configuration in XML format for the current project
help:evaluateCalculate the Maven expression given by the user in interactive mode
help:systemDisplays a list of platform details, such as system properties and environment variables

2. Use help:evaluate to view attribute values

① Define attributes

<properties>
    <com.atguigu.hello>good morning maven</com.atguigu.hello>
</properties>

② Run command

③ Operation results

3. Access system properties through Maven

① Java system properties list

[1] Java code

Properties properties = System.getProperties();
Set<Object> propNameSet = properties.keySet();
for (Object propName : propNameSet) {
    String propValue = properties.getProperty((String) propName);
    System.out.println(propName + " = " + propValue);
}

[2] Operation results

java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = D:\software\Java\jre\bin
java.vm.version = 25.141-b15
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
user.country = CN
user.script =
sun.java.launcher = SUN_STANDARD
sun.os.patch.level =
java.vm.specification.name = Java Virtual Machine Specification
user.dir = D:\idea2019workspace\atguigu-maven-test-prepare
java.runtime.version = 1.8.0_141-b15
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = D:\software\Java\jre\lib\endorsed
os.arch = amd64
java.io.tmpdir = C:\Users\ADMINI~1\AppData\Local\Temp\
line.separator =
java.vm.specification.vendor = Oracle Corporation
user.variant =
os.name = Windows 10
sun.jnu.encoding = GBK
java.library.path = D:\software\Java\bin;C:\WINDOWS\Sun\Java\bin;C:\WIN......
java.specification.name = Java Platform API Specification
java.class.version = 52.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 10.0
user.home = C:\Users\Administrator
user.timezone =
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = UTF-8
java.specification.version = 1.8
java.class.path = D:\software\Java\jre\lib\charsets.jar;D:\softw......
user.name = Administrator
java.vm.specification.version = 1.8
sun.java.command = com.atguigu.maven.MyTest
java.home = D:\software\Java\jre
sun.arch.data.model = 64
user.language = zh
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.8.0_141
java.ext.dirs = D:\software\Java\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = D:\software\Java\jre\lib\resources.jar;D:\sof......
java.vendor = Oracle Corporation
file.separator = \
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = amd64

② Access system properties using Maven

4. Accessing system environment variables

${env. System environment variable name}

5. Accessing project properties

① Meaning
Use the expression ${project.xxx} to access the element values in the current POM.

② Access level 1 label
${project. Tag name}

③ Access sub Tags
${project. Tag name. Sub tag signature}

④ Access list label
${project. Tag name [subscript]}

6. Access settings global configuration

${settings. Tag name} can access settings The element value configured in XML.

7. Use

  • In the current POM Reference attribute in XML file
  • Resource filtering function: reference attributes in non Maven configuration files. Maven will replace the expression of the referenced attribute with the attribute value when processing resources

4, Detailed explanation of build tag

In the actual process of using Maven, we will find that the build tag sometimes has and sometimes does not. What's the matter? In fact, through effective POM, we can see that the relevant configuration of the build tag is always there. Only when we need to customize the construction process, we can override the default value or supplement the configuration by configuring the build tag. We can see this by printing a valid POM.

So in essence: the build tags we configured are the superposition of the super POM configuration. Then why should we stack on the basis of the default configuration? Very simply, customize the build process when the default configuration cannot meet the requirements.

<build>
    <sourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\java</sourceDirectory>
    <scriptSourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\scripts</scriptSourceDirectory>
    <testSourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\test\java</testSourceDirectory>
    <outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\classes</outputDirectory>
    <testOutputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\test-classes</testOutputDirectory>
    <resources>
        <resource>
            <directory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>D:\idea2019workspace\atguigu-maven-test-prepare\src\test\resources</directory>
        </testResource>
    </testResources>
    <directory>D:\idea2019workspace\atguigu-maven-test-prepare\target</directory>
    <finalName>atguigu-maven-test-prepare-1.0-SNAPSHOT</finalName>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.3</version>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2-beta-5</version>
            </plugin>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
            </plugin>
            <plugin>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-clean-plugin</artifactId>
            <version>2.5</version>
            <executions>
                <execution>
                    <id>default-clean</id>
                    <phase>clean</phase>
                    <goals>
                        <goal>clean</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>default-testResources</id>
                    <phase>process-test-resources</phase>
                    <goals>
                        <goal>testResources</goal>
                    </goals>
                </execution>
                <execution>
                    <id>default-resources</id>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>resources</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <executions>
                <execution>
                    <id>default-jar</id>
                    <phase>package</phase>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <executions>
                <execution>
                    <id>default-compile</id>
                    <phase>compile</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
                <execution>
                    <id>default-testCompile</id>
                    <phase>test-compile</phase>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <executions>
                <execution>
                    <id>default-test</id>
                    <phase>test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.4</version>
            <executions>
                <execution>
                    <id>default-install</id>
                    <phase>install</phase>
                    <goals>
                        <goal>install</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.7</version>
            <executions>
                <execution>
                    <id>default-deploy</id>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.3</version>
            <executions>
                <execution>
                    <id>default-site</id>
                    <phase>site</phase>
                    <goals>
                        <goal>site</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\site</outputDirectory>
                        <reportPlugins>
                            <reportPlugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-project-info-reports-plugin</artifactId>
                            </reportPlugin>
                        </reportPlugins>
                    </configuration>
                </execution>
                <execution>
                    <id>default-deploy</id>
                    <phase>site-deploy</phase>
                    <goals>
                        <goal>deploy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\site</outputDirectory>
                        <reportPlugins>
                            <reportPlugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-project-info-reports-plugin</artifactId>
                            </reportPlugin>
                        </reportPlugins>
                    </configuration>
                </execution>
            </executions>
            <configuration>
                <outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\site</outputDirectory>
                <reportPlugins>
                    <reportPlugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-project-info-reports-plugin</artifactId>
                    </reportPlugin>
                </reportPlugins>
            </configuration>
        </plugin>
    </plugins>
</build>

2. build tag composition

From the complete example, we can see that the sub tag of the build tag roughly includes three main parts:

① Define the agreed directory structure

Refer to the following sections in the example:

<sourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\java</sourceDirectory>
<scriptSourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\scripts</scriptSourceDirectory>
<testSourceDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\src\test\java</testSourceDirectory>
<outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\classes</outputDirectory>
<testOutputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\test-classes</testOutputDirectory>
<resources>
    <resource>
        <directory>D:\idea2019workspace\atguigu-maven-test-prepare\src\main\resources</directory>
    </resource>
</resources>
<testResources>
    <testResource>
        <directory>D:\idea2019workspace\atguigu-maven-test-prepare\src\test\resources</directory>
    </testResource>
</testResources>
<directory>D:\idea2019workspace\atguigu-maven-test-prepare\target</directory>

We can see that the functions of each directory are as follows:

Directory nameeffect
sourceDirectoryMain source program storage directory
scriptSourceDirectoryScript source program storage directory
testSourceDirectoryTest source program storage directory
outputDirectoryDirectory main body compilation result
testOutputDirectoryTest source program compilation result output directory
resourcesMain resource file storage directory
testResourcesTest resource file storage directory
directoryBuild result output directory

② Standby plug-in management
The pluginManagement tab holds several rarely used plug-ins:

  • maven-antrun-plugin
  • maven-assembly-plugin
  • maven-dependency-plugin
  • maven-release-plugin

The plug-ins managed through the pluginManagement tag are like dependency management. The version number can be omitted when the child project is used, so as to achieve the effect of unified version management in the parent project. Here are some examples:

  • Plug in information managed by spring boot dependencies:
<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<version>2.6.2</version>
</plugin>
  • Plug in information used by subproject:
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

③ Lifecycle plug-ins

The plugins tag stores the plug-ins actually used in the default life cycle. These plug-ins must be familiar to everyone. Therefore, leaving aside the plug-ins themselves, let's take a look at the structure of the plugin tag:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <executions>
        <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
        <execution>
            <id>default-testCompile</id>
            <phase>test-compile</phase>
            <goals>
                <goal>testCompile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

[1] Coordinate part
artifactId and version tags define the coordinates of the plug-in. As Maven's own plug-in, groupId is omitted here.

[2] Executive part
Multiple execution tags can be configured in the execution tag. In the execution tag:

  • id: Specifies the unique id
  • Phase: associated lifecycle phase
  • goals/goal: associate the goals of the specified lifecycle
    • Multiple goal tags can be configured in the goals tag, indicating that a life cycle phase can correspond to multiple goals of the current plug-in.

In addition, the implementation process of plug-in objectives can be configured. For example, the site objectives of Maven site plugin plug-in:

<execution>
    <id>default-site</id>
    <phase>site</phase>
    <goals>
        <goal>site</goal>
    </goals>
    <configuration>
        <outputDirectory>D:\idea2019workspace\atguigu-maven-test-prepare\target\site</outputDirectory>
        <reportPlugins>
            <reportPlugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
            </reportPlugin>
        </reportPlugins>
    </configuration>
</execution>

The tag used for configuration in the configuration tag is defined by the plug-in itself. Take Maven site plugin as an example. Its core class is org apache. maven. plugins. site. render. Sitemojo, in this class, we see the outputDirectory attribute:

The parent class of SiteMojo is AbstractSiteRenderingMojo. In the parent class, we see the reportPlugins attribute:

Conclusion: the settings that can be made by each plug-in are specified by each plug-in itself, which cannot be generalized.

3. Typical application: specify JDK version

① Ask questions
We are in settings If the JDK version is configured in the XML, the Maven project will be deployed on the server in the future without setting XML configuration, how to ensure the normal operation of the program? During the compilation process, compile plugin is responsible for telling us the information of the specified version of the plugin.

② Temporarily cancel settings XML configuration
In order to test the effect of configuring the Maven compiler plugin plug-in, we temporarily cancel settings profile configuration in XML.

<!-- to configure Maven Project default JDK edition -->
<!-- <profile>
  <id>jdk-1.8</id>
  <activation>
	<activeByDefault>true</activeByDefault>
	<jdk>1.8</jdk>
  </activation>
  <properties>
	<maven.compiler.source>1.8</maven.compiler.source>
	<maven.compiler.target>1.8</maven.compiler.target>
	<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
  </properties>
</profile> -->

③ Write source code
Obviously, Lambda expressions are used here, which is the syntax only supported by JDK 1.8.

package com.atguigu.maven;

public class Hello {

    public void hello() {
        new Thread(()->{
            System.out.println("thread ...");
        }).start();
    }
}

At this point, we execute the compile command:

④ Configuration build process

<!-- build Label: it means to tell Maven,Your build behavior, I'm going to start customizing! -->
<build>
    <!-- plugins label: Maven Listen to me, you need to use these plug-ins when you build them for me! -->
    <plugins>
        <!-- plugin Tag: This is a specific plug-in I want to specify -->
        <plugin>
            <!-- Coordinates of the plug-in. Referenced here maven-compiler-plugin The plug-in is not a third party, but a Maven Built in plug-ins. -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            
            <!-- configuration Labels: configuring maven-compiler-plugin plug-in unit -->
            <configuration>
                <!-- The specific configuration information will vary due to different plug-ins and requirements -->
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

⑤ Execute the compile command again

⑥ Comparison of two configuration methods

  • settings. Configuration in XML: it only takes effect locally if it is separated from the current settings If XML can cover the scope, it cannot take effect.
  • In the current Maven project POM Configuration in XML: no matter in which environment you perform compilation and other build operations, it is effective.

⑦ Supplementary notes

[1]source label meaning
View Maven's official website page , we find the description of the source tag:

The - source parameter passed in when calling the Java compiler command. What does the - source parameter mean for the compiler?

My understanding of the sentence "provide source compatibility with the specified distribution" is:

We write code according to JDK 1.8 - this is the "source" in "source compatibility".
The specified distribution is JDK 1.8 we specified.
Who is compatible with whom? Now the source code is established, so the compiler is required to use the specified JDK version to be compatible with our source code.

In addition, we also see:

This function can also be realized by configuring Maven. Com in the properties tab compiler. Source attribute. So we often see configurations like this:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

[2] Meaning of target tag

The - target parameter passed in when calling the Java compiler command. What does the - target parameter mean for the compiler?

My understanding of the sentence "generate class files for specific VM versions" is:

VM means JVM
class files refer to * class bytecode file
The overall meaning is the *. Generated after the source file is compiled The class bytecode file should conform to the specified JVM version

4. Typical application: spring boot customized packaging

① Demand
Obviously, spring boot Maven plugin is not Maven's own plug-in, but provided by SpringBoot to change Maven's default build behavior. Specifically, change the packaging behavior. By default, Maven calls the jar target of Maven jar plugin plug-in to generate ordinary jar packages.

Ordinary jar packages cannot use Java - jar XXX Jar is used to start and run, but the design concept of SpringBoot is that each "micro service" is exported as a jar package, which can use Java - jar XXX A command like jar starts running directly.

In this way, the packaging method must be adjusted. Therefore, SpringBoot provides a spring boot Maven plugin to customize the packaging behavior.

② Sample code
Everything has been encapsulated by SpringBoot, so the configuration is very simple. Just provide the plug-in coordinates.

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<version>2.5.5</version>
		</plugin>
	</plugins>
</build>

③ Seven goals of plug-ins

Target nameeffect
spring-boot:build-imagePackage an application into a OCI image using a buildpack.
spring-boot:build-infoGenerate a build-info.properties file based on the content of the current MavenProject.
spring-boot:helpDisplay help information on spring-boot-maven-plugin.
Call mvn spring-boot:help -Ddetail=true -Dgoal= to display parameter details.
spring-boot:repackageRepackage existing JAR and WAR archives so that they can be executed from the command line using java -jar. With layout=NONE can also be used simply to package a JAR with nested dependencies (and no main class, so not executable).
spring-boot:runRun an application in place.
spring-boot:startStart a spring application. Contrary to the run goal, this does not block and allows other goals to operate on the application. This goal is typically used in integration test scenario where the application is started before a test suite and stopped after.
spring-boot:stopStop an application that has been started by the 'start' goal. Typically invoked once a test suite has completed.

5. Typical application: Mybatis reverse engineering

Reverse engineering using Mybatis requires the following configurations. The MBG plug-in is characterized by the need to provide the dependencies required by the plug-in:

<!-- control Maven Related configuration during construction -->
<build>
		
	<!-- Plug ins used in the construction process -->
	<plugins>
		
		<!-- For specific plug-ins, the operation of reverse engineering appears in the form of plug-ins in the construction process -->
		<plugin>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-maven-plugin</artifactId>
			<version>1.3.0</version>
	
			<!-- Plug in dependencies -->
			<dependencies>
				
				<!-- Core dependence of reverse engineering -->
				<dependency>
					<groupId>org.mybatis.generator</groupId>
					<artifactId>mybatis-generator-core</artifactId>
					<version>1.3.2</version>
				</dependency>
					
				<!-- Database connection pool -->
				<dependency>
					<groupId>com.mchange</groupId>
					<artifactId>c3p0</artifactId>
					<version>0.9.2</version>
				</dependency>
					
				<!-- MySQL drive -->
				<dependency>
					<groupId>mysql</groupId>
					<artifactId>mysql-connector-java</artifactId>
					<version>5.1.8</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

6. Summary

I don't know if you have found that when we usually need to use the build tag, the bottom layer will help us package it, and there are not many places we need to configure. Even if some places need our configuration, we won't really write it ourselves. Just copy the ready-made cases.

So we can understand the label.

5, Dependency configuration supplement

Maven official website introduces the dependency mechanism (opens new window)

1. Dependent range

①import
The most basic way to manage dependencies is to inherit from the parent project, but like Java classes, Maven inherits only. What if the dependency information of different systems is encapsulated in different POM s and cannot inherit multiple parent projects? In this case, you can use the import dependency scope.

Of course, a typical case is the introduction of SpringBoot and SpringCloud dependencies into the project:

<dependencyManagement>
    <dependencies>

        <!-- SpringCloud Dependency import -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR9</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <!-- SpringCloud Alibaba Dependency import -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.2.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <!-- SpringBoot Dependency import -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.3.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

import dependency scope usage requirements:

  • Package type must be pom
  • Must be placed in dependencyManagement

The official website is described as follows:

This scope is only supported on a dependency of type pom in the <dependencyManagement> section. 
It indicates the dependency is to be replaced with the effective list of dependencies in the specified POM's <dependencyManagement> section.
Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

②system
Take the development under Windows system environment as an example. Suppose D: \ tempore \ atguigu-maven-test-aaa-1.0-snapshot Jar wants to be introduced into our project. At this time, we can configure the dependency as the system scope:

<dependency>
    <groupId>com.atguigu.maven</groupId>
    <artifactId>atguigu-maven-test-aaa</artifactId>
    <version>1.0-SNAPSHOT</version>
    <systemPath>D:\tempare\atguigu-maven-test-aaa-1.0-SNAPSHOT.jar</systemPath>
    <scope>system</scope>
</dependency>

But it's obvious: introducing dependencies like this is not portable at all, so don't use it. If you need to introduce jar packages outside the system, we will talk about special methods later.

③runtime
It is specially used for jar packages that are not required at compile time but are required at run time. For example, when compiling, we call methods according to the interface, but what we need in actual operation is the implementation class of the interface. Typical cases are:

<!--Hot deployment -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

2. Optional dependency

① Configuration example

<!--Hot deployment -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

② Essential meaning
Optional is actually "optional". The official website explains:

Its core meaning is: Project X depends on Project A, and some codes in A that x can't use depend on B, so B is "optional" for X.

3. Version arbitration (shortest path, declaration order)

① Shortest path first
In the example below, Maven will adopt version 1.2.12 for module pro25-module-a.

② When the paths are the same, the first declaration takes precedence

At this time, which version Maven adopts depends on which of the two modules pro30-module-y and pro31-module-z in pro29-module-x is declared first.

③ Summary
In fact, Maven's version arbitration mechanism is just a way to decide the jar package version independently without human intervention. In fact, which version we want to use depends on the actual situation in the project. Therefore, under the normal operation of the project, the jar package version can be arbitrated by maven, so we don't have to worry about it; In case of conflict, the version determined by Maven arbitration cannot meet the requirements. At this time, the programmer should clearly specify the jar package version.

6, Maven custom plug-in

1. Positioning of this section
In fact, there are few scenarios in actual development that require us to develop custom Maven plug-ins, so this section only helps us better understand the relationship between plug-in objectives and life cycle stages from this perspective.

2. Plug in development

① Create project
[omitted]

② Set packaging method

<packaging>maven-plugin</packaging>

③ Introduce dependency
Choose one of the following two methods:

[1] Annotations will be used in document annotations in the future

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-plugin-api</artifactId>
    <version>3.5.2</version>
</dependency>

[2] Annotations will be used directly in the future

<dependency>
    <groupId>org.apache.maven.plugin-tools</groupId>
    <artifactId>maven-plugin-annotations</artifactId>
    <version>3.5.2</version>
</dependency>

④ Create Mojo class
The Mojo class is the core class of a Maven plug-in.

The word Mojo means Maven Old Java Object. In fact, the word Mojo itself contains magic; Spell (bag); amulet; The meaning of (human) charm. Maven uses Mojo because it is a small joke on POJO.

[1] Mojo interface
Every mojo needs to implement org apache. maven. plugin. Mojo interface.

[2] AbstractMojo abstract class
It is difficult for us to implement the Mojo interface. Fortunately, we can inherit AbstractMojo. At this time, we only need to implement the execute() method.

public class MyHelloPlugin extends AbstractMojo {
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("---> This is my first maven plugin. <---");
    }
}

3. Plug in configuration

① Configuration in Mojo class
[1] Notes used in document notes
Corresponding POM Dependency in XML: Maven plugin API

[2] Mark annotations directly on the class
Corresponding to POM Dependencies in XML: Maven plugin annotations

// Name attribute: Specifies the target name
@Mojo(name = "firstBlood")
public class MyPluginOfFistBlood extends AbstractMojo {
    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("---> first blood <---");
    }
}

② Install plug-ins
To use the plug-in later, you must install the plug-in at least to the local warehouse.

③ Register plug-ins
We need to register the groupId part in the plug-in coordinates to settings XML.

<pluginGroups>
	<!-- pluginGroup
	 | Specifies a further group identifier to use for plugin lookup.
	<pluginGroup>com.your.plugins</pluginGroup>
	-->
	<pluginGroup>com.atguigu.maven</pluginGroup>
</pluginGroups>

4. Using plug-ins

① Identify plug-in prefix
Maven identifies the plug-in prefix according to the artifact ID of the plug-in. For example, there are two cases:

[1] Pre matching

  • Matching rule: ${prefix} - Maven plugin
  • artifactId: hello-maven-plugin
  • Prefix: hello

[2] Intermediate matching

  • Matching rule: $- prefix -}
  • artifactId: maven-good-plugin
  • Prefix: good

② Directly on the command line
Command:

mvn hello:sayHello

effect:

③ Configure in the build tab
It's persuasive to find a Maven project configuration that has nothing to do with plug-ins.

[1] Disposition

<build>
	<plugins>
		<plugin>
			<groupId>com.atguigu.maven</groupId>
			<artifactId>hello-maven-plugin</artifactId>
			<version>1.0-SNAPSHOT</version>
			<executions>
				<execution>
                    <id>hello</id>
                    <!-- Specifies the lifecycle phase associated with the target -->
					<phase>clean</phase>
					<goals>
						<goal>sayHello</goal>
					</goals>
				</execution>
                <execution>
                    <id>blood</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>firstBlood</goal>
                    </goals>
                </execution>
			</executions>
		</plugin>
	</plugins>
</build>

[2] Effect

[3] Use of graphical interface

[4] Command line usage
Execute the lifecycle bound to the plug-in target:

7, profile details

1. profile overview

① Word interpretation

Here we can connect the meaning of "side" in the word profile: each running environment of the project is equivalent to a side of the whole project.

② Different operating environments of the project

Generally, we have at least three operating environments:

  • Development environment: each module developed by different development engineers can call and access each other; Internal use
  • Test environment: for the test engineer to test the function of each module of the project; Internal use
  • Production environment: for end-users to access - so this is the formal operating environment to provide external services

The "environment" here is still a general term. In practice, a complete set of operating environment will include many different servers:

  • MySQL
  • Redis
  • ElasticSearch
  • RabbitMQ
  • FastDFS
  • Nginx
  • Tomcat
  • ......

Take MySQL for example. The access parameters in different environments must be completely different:

development environment testing environmentproduction environment
dev.driver=com.mysql.jdbc.Driver
dev.url=jdbc:mysql://124.71.36.17:3306/db-sys
dev.username=root
dev.password=atguigu test.driver=com.mysql.jdbc.Driver
test.url=jdbc:mysql://124.71.36.89:3306/db-sys
test.username=dev-team
test.password=atguigu product.driver=com.mysql.jdbc.Driver
product.url=jdbc:mysql://39.107.88.164:3306/prod-db-sys
product.username=root
product.password=atguigu

But there is only one set of code. If in JDBC It's too troublesome to change back and forth in properties, and it's easy to omit or make mistakes, which increases the difficulty and workload of debugging. Therefore, the best way is to prepare the configuration information applicable to different environments, and activate the configuration in which environment to deploy.

In Maven, the profile mechanism is used to manage the configuration information in different environments. However, similar mechanisms to solve similar problems exist in other frameworks, and from the perspective of module division, the information of the persistence layer is configured in the construction tool, which also violates the principle of "high cohesion and low coupling".

So we can understand Maven's profile without going into it.

③ Basic logic of profile declaration and use

  • First, declare a profile for each environment
    • Environment A: profile A
    • Environment B: profile B
    • Environment C: profile C
    • ......
  • Then activate a profile

④ Default profile

In fact, even if we're in POM The profile tag is not configured in XML, and profile has been used. Why? Because all labels under the root label project are equivalent to setting the default profile. In this way, we can easily understand the following sentence: under the project tag, except modelVersion and coordinate tag, other tags can be configured into the profile.

2. profile configuration

① External perspectives: Profiles
From an external perspective, the profile can be configured in the following two configuration files:

  • settings.xml: global validation. Among them, we are most familiar with configuring JDK 1.8.
  • pom.xml: the current POM takes effect

② Internal implementation: specific label
From an internal perspective, the configuration profile has the following syntax requirements:

[1] Profiles / profiles tab

  • Since the profile naturally represents one of many optional configurations, it is uniformly managed by the plural profiles tag.
  • Because the profile tag overrides POM The default configuration in XML, so the profiles tag is usually POM The last tag in the XML.

[2]id tag
Each profile must have an id tag that specifies the unique identification of the profile. The value of this id tag will be used when calling profile from the command line. The format of this command is: - D.

[3] Other allowable labels
A profile can cover the final name of the project, project dependencies, plug-in configuration and other aspects to affect the construction behavior.

  • build
    • defaultGoal
    • finalName
    • resources
    • testResources
    • plugins
  • reporting
  • modules
  • dependencies
  • dependencyManagement
  • repositories
  • pluginRepositories
  • properties

3. Activate profile

① The default configuration is activated by default
As mentioned earlier, what is not in the profile tab in POM is the default profile. Of course, it is activated by default.

② Activation based on environmental information
Environment information includes JDK version, operating system parameters, files, attributes and other aspects. Once a profile is activated, all the configurations it defines will overwrite the elements of the corresponding hierarchy in the original POM. You can refer to the following label structure:

<profile>
	<!--Unique identification-->
	<id>dev</id>
	<!--Activation mode-->
    <activation>
        <!-- Configure whether to activate by default -->
    	<activeByDefault>false</activeByDefault>
		<!--Identify current profile Can be based on JDK Version activation-->
        <jdk>1.5</jdk>
        <!--Identify current profile It can be activated according to the operating system-->
        <os>
        	<name>Windows XP</name>
            <family>Windows</family>
            <arch>x86</arch>
            <version>5.1.2600</version>
        </os>
        <property>
        	<name>mavenVersion</name>
            <value>2.0.5</value>
        </property>
        <file>
        	<exists>file2.properties</exists>
            <missing>file1.properties</missing>
        </file>
    </activation>
</profile>

Here is a question: what is the relationship between multiple activation conditions?

  • Before Maven 3.2.2: the relationship between or can be activated when the first condition is met.
  • Maven 3.2.2 start: all conditions need to be met - and the relationship between them.

Let's take a concrete example. Assuming the following profile configuration, it is activated when JDK version is 1.6:

<profiles>
	<profile>
    	<id>JDK1.6</id>
        <activation>
            <!-- The specified activation conditions are: JDK 1.6 -->
        	<jdk>1.6</jdk>
        </activation>
        ......
    </profile>
</profiles>

It should be pointed out here that Maven will automatically detect the JDK version installed in the current environment. As long as the JDK version starts with 1.6, it is qualified. The following examples are consistent:

  • 1.6.0_03
  • 1.6.0_02
  • ......

③ Command line activation
[1] List active profile s

# List all active profile s and where they are defined
mvn help:active-profiles

[2] Specify a specific profile

mvn compile -P<profile id>

4. Operation example

① Write Lambda expression code

Lambda expression code requires that the JDK version must be 1.8. We can judge whether a profile with a specified lower JDK version is activated and effective.

@Test
public void test() {
    new Thread(()->{
        System.out.println(Thread.currentThread().getName() + " is working");
    }).start();
}

Run this test method with the current configuration:

② Configure profile

<profiles>
    <profile>
        <id>myJDKProfile</id>
        <!-- build Label: it means to tell Maven,Your build behavior, I'm going to start customizing! -->
        <build>
            <!-- plugins label: Maven Listen to me, you need to use these plug-ins when you build them for me! -->
            <plugins>
                <!-- plugin Tag: This is a specific plug-in I want to specify -->
                <plugin>
                    <!-- Coordinates of the plug-in. Referenced here maven-compiler-plugin The plug-in is not a third party, but a Maven Built in plug-ins. -->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>

                    <!-- configuration Labels: configuring maven-compiler-plugin plug-in unit -->
                    <configuration>
                        <!-- The specific configuration information will vary due to different plug-ins and requirements -->
                        <source>1.6</source>
                        <target>1.6</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

③ Execute build command

mvn clean test -PmyJDKProfile

5. Resource attribute filtering

① Introduction
Maven provides a mechanism of "resource attribute filtering" in order to switch between different operating environments through profile. Through attribute replacement, different environments use different parameters.

② Operation demonstration
[1] Configure profile

<profiles>
    <profile>
        <id>devJDBCProfile</id>
        <properties>
            <dev.jdbc.user>root</dev.jdbc.user>
            <dev.jdbc.password>atguigu</dev.jdbc.password>
            <dev.jdbc.url>http://localhost:3306/db_good</dev.jdbc.url>
            <dev.jdbc.driver>com.mysql.jdbc.Driver</dev.jdbc.driver>
        </properties>
        <build>
            <resources>
                <resource>
                    <!-- Indicates that the resource filtering function is enabled for the directory specified here -->
                    <directory>src/main/resources</directory>

                    <!-- Turn on the resource filtering function -->
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    </profile>
</profiles>

[2] Create pending resource files

dev.user=${dev.jdbc.user}
dev.password=${dev.jdbc.password}
dev.url=${dev.jdbc.url}
dev.driver=${dev.jdbc.driver}

[3] Execute commands to process resources

mvn clean resources:resources -PdevJDBCProfile

[4] Locate the processed resource file

[5] Extend
From time to time, we will see the include and exclude tags under the resource tag. Their functions are:

  • includes: Specifies the resources to be included in the target location when the resource phase is executed
  • excludes: Specifies the resources to exclude when executing the resource phase

Take the following example:

<build>
    <resources>
        <resource>
            <!-- Indicates that the resource filtering function is enabled for the directory specified here -->
            <directory>src/main/resources</directory>

            <!-- Turn on resource filtering -->
            <filtering>true</filtering>

            <includes>
                <include>*.properties</include>
            </includes>

            <excludes>
                <exclude>happy.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Execute the command to process resources:

mvn clean resources:resources -PdevJDBCProfile

The implementation effect is as follows:

Of course, we only take the properties file as an example, not only the properties file.

Tags: Java git Maven

Posted by Craig79 on Sun, 01 May 2022 15:17:45 +0300