Maven - Configuration Management

Keywords: Java Maven Apache Junit

Maven

Maven is an automated build tool that focuses on project building and dependency management for the Java platform. Project Object Model: Project Object Model. The information of Java project is encapsulated as object form, which is convenient for operation and management.

Maven action

1 add the third-party jar package: after using Maven, only one copy of each jar package needs to be saved in the local warehouse

2. Dependencies between jar packages: Maven can automatically import all other jar packages that the current jar package depends on

3 handling the conflict between jar packages: Maven has two built-in dependency principles: the shortest path first and the declarant first. Can automatically handle the conflict between jar packages

Get the third-party jar package: Maven will automatically download it from the central warehouse, and download other jar packages that this jar package depends on at the same time -- standard, complete and accurate! Solve all problems at once

5. Split the project into multiple engineering modules: Maven's dependency management mechanism can split the project into multiple Engineering Collaborative Development

6 realize the distributed deployment of the project: after the project is divided into multiple modules, each module can run on an independent server. We call it distributed deployment

Core concepts

① POM ② agreed directory structure ③ coordinates ④ dependency management ⑤ warehouse management ⑥ life cycle ⑦ plug-ins and objectives ⑧ inheritance ⑨ aggregation

Configure local warehouse

Tags in Maven's core configuration file: D:\apache-maven-3.5.0\conf\settings.xml

< localrepository > D: / repmaven < / localrepository > (specify local repository file path)

Configure the Alibaba image server in the mirrors tab of the settings.xml file

    <mirror>
      <id>alimaven</id>
      <mirrorOf>central</mirrorOf>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>

Automated build

Java EE development generally agrees with the view: Convention > configuration > coding. It means that the problem that can be solved by configuration will not be encoded, and the problem that can be solved by convention will not be configured. Maven finds java source files from the directory of project root > / SRC / main / Java by default. The compiled class files will be saved in the directory of project root > / target / classes. In maven, all POS have a root object, Super POM. All default configuration items are defined in Super POM

Build: the Java code is compiled to get the corresponding. class file, which "takes" the compiled result of the Web project to the specified directory structure on the server. We call deployment. In addition to this, in the actual project, it also includes the jar package of the third-party framework and various configuration files. Must be deployed to the server according to the correct directory structure to run. And these Maven commands can help me build it automatically. It corresponds to the content in pom.xml, that is, the < build > element. That is, Lifecycle

Construction link

① clean up: delete the previous compilation results to prepare for recompilation

② compile: compile Java source program into bytecode file

③ test: test the key points in the project to ensure the correctness of the key points in the iterative development process

④ report: record and display test results in standard format after each test

Package: package a project containing many files into a compressed file for installation or deployment. Java project corresponds to jar package, Web project corresponds to war package

⑥ installation: in Maven environment, it refers to the installation of the packaged result jar package or war package into the local warehouse

⑦ deployment: deploy the packaged results to the remote warehouse or deploy the war package to the server to run

life cycle

● Maven life cycle defines the execution sequence of each construction phase. With this list, Maven can automatically execute the construction commands.

● Maven has three independent life cycles:

① Clean Lifecycle does some cleaning work before the real construction.

② the core part of Default Lifecycle construction, compilation, testing, packaging, installation, deployment, etc.

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

They are independent of each other. You can just call clean to clean up the working directory and site to generate the site. Of course, you can also run mvn clean install site directly to run all three life cycles. Each life cycle consists of a set of phases. The commands we usually enter on the command line always correspond to a specific phase.

When you run any phase, all the previous phases are run. However, the life cycle is abstract (Maven's life cycle itself does not do any actual work), and task execution (such as compiling source code) is done by plug-ins. The plug-in mechanism of Maven is completely dependent on the life cycle of Maven. The so-called plug-in is actually a maven project, but this project will reference some API s of maven, and the plug-in project also has Maven coordinates.

Plug ins and targets

● the phase of the life cycle is bound with the goal goal of the plug-in to complete the actual construction task

● each plug-in can realize multiple functions, and each function is a plug-in goal.

● Maven's lifecycle is tied to the plug-in goals to accomplish a specific build.

The syntax of maven command is mvn [options] [goal(s)] [phase(s)]

For example: MVN compiler: before the compile colon is the plug-in prefix, followed by the plug-in target or function

clean removes all files generated by the last build

Site generates site documents for the project

deploy deploys the generated site documents to a specific server

Inheritance, dependency, aggregation

Maven's aggregation feature enables multiple modules of the project to be built together, while inheritance helps extract the same dependency, plug-in and other configurations of each module, while simplifying module configuration and maintaining the consistency of each module

Any Maven project is implicitly inherited from Super POM Therefore, a large number of configurations of super POM will be inherited by all Maven projects, and these configurations have become the conventions advocated by Maven
 
When a module project introduces another module or a third-party jar package, we call them dependent. Dependence has direct dependence and indirect dependence, and defines the scope and principle of dependence among others

Father POM

Note: the packing method should be set to pom

<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.gc.atcrowdfunding</groupId> <artifactId>atcrowdfunding-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <description>Parent project,Aggregate other projects</description> <!-- version management--> <properties> <junit.version>4.12</junit.version> </properties> <> <dependencies> <!-- Public dependence --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement> <!-- Aggregate management --> <modules> <module>../atcrowdfunding-common</module> <module>../atcrowdfunding-manager</module> </modules> </project>

Coordinates: three vectors are used to determine a maven project in Maven's warehouse, which can be used for dependency or inheritance of other project modules

[1] groupId: reverse domain name of company or organization + current project name

[2] artifactId: module name of the current project

[3] version: the version of the current module

Our own Maven project must be install ed to enter the warehouse. We can find the corresponding jar package in the warehouse through the coordinates. Join three vectors of gav and add a-v

\cn\gc\maven\maven1\0.0.1-SNAPSHOT\maven1-0.0.1-SNAPSHOT.jar

[4] packaging: packaging mechanism, such as pom,jar, Maven plugin, ejb, war, ear, rar, par, jar -- >

pom packaging parent project, war packaging Web project, jar packaging general project

[5] properties: define some constants for pom, which can be directly referenced elsewhere in pom to control version number

How to use ${junit.version}

[6] dependency management: manage dependencies in the parent project

All the jar packages introduced in the parent project will be inherited by the child project, but sometimes we do not need the jar packages in the parent project. We can enclose the dependencies label in the parent project with the dependency management label, so that the version of the jar package needed by the child project can be directly managed by the parent project by introducing the corresponding groupId and artifactId

[7] dependencies define the dependencies of the project

In this tag, such a module needs to introduce the jar package, which only needs to be defined in this sub tag dependency. Several principles of dependency management

The dependent scope contains the following values: compile, provided, runtime, test, system

The default value is compile. If A depends on B and B depends on C, then A → B and B → C are both direct dependencies, while A → C is indirect dependency. Through the dependency range, you can control whether there is A direct dependency

① compile (default)

The Java code in the [1]main directory can access the dependency of this range

The Java code in the [2]test directory can access the dependency of this scope

[3] it should be placed in the lib directory of WEB-INF when it is deployed to Tomcat server

    ② test

The Java code in the [1]main directory cannot access the dependency of this range

The Java code in the [2]test directory can access the dependency of this scope

[3] it will not be placed in the lib directory of WEB-INF when deployed to Tomcat server

    ③ provided

The Java code in the [1]main directory can access the dependency of this range

The Java code in the [2]test directory can access the dependency of this scope

[3] it will not be placed in the lib directory of WEB-INF when deployed to Tomcat server

④ runtime [understanding]

The Java code in the [1]main directory cannot access the dependency of this range

The Java code in the [2]test directory can access the dependency of this scope

[3] when deployed to Tomcat server, it will be placed in the lib directory of WEB-INF

Principle of dependency: resolving jar package conflicts

① the shortest path is preferred

(2) when the paths are the same, the one declared first takes precedence. Order refers to the order of dependency label configuration

Dependency exclusion: indirect dependencies that may be duplicated can be excluded to ensure the program is correct. You can also rely on other versions after exclusion

    <!-- Dependency exclusion -->
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
 
When the dependency, plug-in version, configuration and other information are declared in the parent POM, the child module does not need to declare these information when it is used, nor will the dependency versions used by multiple child modules be inconsistent, which reduces the probability of dependency conflict. In addition, if the child module does not explicitly declare the dependency and plug-in use, even if it has been in the dependency management, P of the parent POM Lugin management is configured and will not produce actual effect
[8] modules: the core to realize aggregation. The module value is the relative path between the aggregated module and the aggregated POM. Each aggregated module also contains pom.xml, src/main/java, src/test/java, etc

Sub engineering POM

<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>atcrowdfunding-manager</artifactId>
  <description>Controller class,Business layer interface and implementation class, Dao Interface and mapping file</description>
  <!--Reference parent project in child project-->
  <parent>
      <groupId>cn.gc.atcrowdfunding</groupId>
      <artifactId>atcrowdfunding-parent</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <relativePath>../atcrowdfunding-parent/pom.xml</relativePath>
  </parent>
  <dependencies>
   <!--Introduce parent project module-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>
   <!--Construction management-->
  <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.42</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
  </build>
</project>

  

[9] parent: used to determine the coordinate position of the parent project

relativePath: Specifies the path to find the pom.xml of the parent project from the pom.xml file of the current child project

If the groupId and version of the child project are duplicate with the parent project, they can be deleted

To reassign the required dependencies in a subproject, you do not need to change the scope and version number of the module, because the parent project has helped manage

Maven configuration details reprint

SuperPom
<!-- START SNIPPET: superpom -->
<project>
  <modelVersion>4.0.0</modelVersion>

  <!-- The central warehouse and plug-in warehouse are defined, All are:https://repo.maven.apache.org/maven2 -->
  <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>

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

  <!-- All kinds of codes, resources, output directories and final component name formats are defined in turn, This is it. Maven Agreement on project structure -->
  <build>
    <directory>${project.basedir}/target</directory>
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <finalName>${project.artifactId}-${project.version}</finalName>
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <scriptSourceDirectory>${project.basedir}/src/main/scripts</scriptSourceDirectory>
    <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
    <resources>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>${project.basedir}/src/test/resources</directory>
      </testResource>
    </testResources>

    <!-- Set version for core plug-ins -->
    <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.3.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <!-- Define project report output path -->
  <reporting>
    <outputDirectory>${project.build.directory}/site</outputDirectory>
  </reporting>

  <!-- Definition release-profile, Attach source code and documentation to the component -->
  <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</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>
<!-- END SNIPPET: superpom -->

Posted by yobo on Sun, 09 Feb 2020 02:35:47 -0800