编程知识 cdmana.com

Java notes: Maven software dependency management

Maven Software dependency management

The outline

  1. Quick start

    • Environment building
    • IDEA Create project
    • Directory structure analysis
  2. Advanced master

    • repository Warehouse analysis
    • pom.xml Configuration details
    • GAV Software positioning coordinates
    • mvn command & Life cycle
    • maven Projects are built manually
    • maven Project auto build
  3. Advanced applications

    • Dependency range resolution
    • Dependencies under project inheritance
    • Dependencies under project aggregation
    • Project common plug-in configuration
    • Private Server Management
  4. Application expansion

    • Basic applications :Java SE project
    • App upgrade :Java WEB project
    • Application expansion :SSM The project build
    • Application expansion :SpringBoot project
    • Application expansion : Test project application

summary

Maven: A tool for automatically building projects and managing project dependencies

Environment building
1、 JDK
Java Development Kit
JAVA_HOME CLASSPATH PATH

$ java -version
java version "1.8.0_251"

2、 Maven
MAVEN_HOME version1
M2_HOME version2
PATH version3

Download address
https://maven.apache.org/

Configure environment variables

vim ~/.bash_profile

# maven
export MAVEN_HOME=/Users/Applications/apache-maven-3.6.3
export PATH=$PATH:$MAVEN_HOME/bin

see maven edition

$ mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)

3、 IDEA

Maven Create project

To configure IDEA Of Maven route , Choose the path of your custom installation

1、 Fast build web project
choice Maven project maven-archetype-webapp

2、 management Maven rely on , Analyze dependencies

Search depends on address :https://mvnrepository.com/

pom.xml Add dependency

<dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>
</dependencies>

Plug in list :https://maven.apache.org/plugins/index.html

pom.xml Add the plug-in

<plugins>
    <pluginManagement>
        <build>
            <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

3、 Run the project , testing Maven project

(1)Maven

Run the command

$ mvn tomcat7:run

Can be configured to start the command

 choice Maven -> Command line add to tomcat7:run

(2) Add to Tomcat

Configure startup commands

 choice Tomcat -> Deployment -> Artifact

4、 Firewalls affect access to foreign warehouses :
[Info] Generating project in Batch mode

Configure alicloud central warehouse

https://maven.aliyun.com/mvn/guide

$ vim ~/.m2/settings.xml
<mirrors>
    <mirror>
      <id>aliyunmaven</id>
      <mirrorOf>*</mirrorOf>
      <name> Alibaba cloud public warehouse </name>
      <url>https://maven.aliyun.com/repository/public</url>
    </mirror>
</mirrors>

Project structure

.
├── pom.xml
├── src               # source
│   └── main
│       ├── java      #  Business code 
│       ├── resources #  Resource file 
│       └── webapp
│           ├── WEB-INF
│           │   └── web.xml
│           └── index.jsp
└── target            #  Target file  

pom.xml
project object model Project object model
package object management Dependency package object manager

Maven Basic operation

1、 Warehouse Repository

Default path of configuration file :~/.m2/settings.xml

  1. Remote warehouse / The central warehouse / Domestic image warehouse
<mirror>
    <id>alimaven</id>
    <mirrorOf>central</mirrorOf>
    <name>aliyun maven</name>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>
  1. Local repository
<localRepository>~/.m2/repository</localRepository>
  1. Private server

Maven To configure

Global configuration settings.xml

<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
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
    <!--  Local warehouse configuration : Default ~/.m2/repository[ It is recommended to modify the configuration ] -->
    <localRepository>${user.home}/.m2/repository</localRepository>

    <!--  Interactive mode configuration , Read user input [ Just use the default , Rarely modified ] -->
    <interactiveMode>true</interactiveMode>

    <!--  Whether to enable independent plug-in configuration files , In general, it is rarely used [ The default can be , Rarely modified ] -->
    <usePluginRegistry>false</usePluginRegistry>

    <!--  Whether to enable offline build mode , Generally, it is seldom modified [ If you can't connect to the Internet for a long time, you can modify ] -->
    <offline>false</offline>
  
    <!--  Is plug-in enabled groupId Automatic scanning [ Rarely used , Full information configuration is recommended when configuring plug-ins ] -->
    <pluginGroups></pluginGroups>

    <!-- Configure some settings of the server, such as authentication information (eg:  account number 、 password ) -->
    <servers></servers>

    <!--  Mirror position  -->
    <mirrors></mirrors>

    <!--  agent  -->
    <proxies></proxies>

    <profiles></profiles>

    <activeProfiles></activeProfiles>

    <activation></activation>

    <properties></properties>

    <repositories></repositories>

</settings>

jdk1.8_profile.xml

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

Project configuration pom.xml

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

<!-- 1、 Project basic information configuration  -->
<!-- 2、 Project construction environment configuration  -->
<!-- 3、 Project warehouse management configuration  -->
<!-- 4、 Project dependency management configuration  -->
<!-- 5、 Project report information configuration  -->
<!-- 6、 Project part distribution configuration  -->
</project>

priority :

 Project configuration pom.xml >  User configuration settings.xmlnote >  Global configuration settings.xml

Full configuration :
Maven: settings.xml、pom.xml Full configuration

GAV coordinate

Version number :

 Software name . The major version number . Minor version number . Stage version number . Letter version number 

Letter version number :
alpha Internal version
beta Public beta
rc Candidate Edition
stable Stable version
release/r/ga Release
final The final version

Maven The command operation

1、 Project build command

mvn --version
mvn archetype:generate

2、 Project clean up 、 compile 、 pack

mvn clean
mvn compile
mvn package

3、 Project operation 、 test 、 Release

mvn tomcat:run
mvn test
mvn site
mvn dependency:tree
mvn install
mvn deploy

Maven Life cycle

clean lifecycle Clean up before project construction
default lifecycle Project compilation and packaging
site lifecycle Project report , Site information , Release link

structure Maven project

1、 Hand built Maven project

Project structure

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── demo
    │   │           └── Hello.java
    │   └── resources
    └── test
        ├── java
        │   └── com
        │       └── demo
        └── resources

pom.xml file
https://maven.apache.org/guides/getting-started/index.html

<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>com.demo</groupId>
  <artifactId>hello</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>jar</packaging>

</project>

Hello.java

package com.demo;

public class Hello{
    
    public static void main(String[] args){
    
        System.out.println("Hello");
    }
}
#  clear 
$ mvn clean

#  compile 
$ mvn compile

#  function 
$ mvn exec:java -Dexec.mainClass="com.demo.Hello"

2、 Command build Maven project

Create command

# <3.0.5
mvn archetype:create

# >3.0.5
mvn archetype:generate

Parameters

-DgroupID=""
-DartifactID=""
-DpackageName=""
-DarchetypeArtifactId="maven-archetype-quickstart/maven-archetype-webapp"
-DinteractiveMode=false

eg:

$ mvn archetype:generate \
-DgroupId=com.demo \
-DartifactId=java-demo \
-DpackageName=com.demo \
-DarchetypeArtifactId=maven-archetype-quickstart

3、 Tool building Maven project

Use IDEA establish Maven project

archetype Slow loading of project skeleton

Copy archetype-catalog.xml To directory

~/.m2/repository/org/apache/maven/archetype/archetype-catalog/3.1.2

IDEA Build Tools -> Maven Runner Set up VM Options:

-DarchetypeCatalog=local

Customize archetype The project skeleton solves the version problem

windows If an error is reported, it needs to be modified

mvn.cmd -> mvn.bat
#  Build the project skeleton 
$ mvn archetype:create-from-project

#  Install to local warehouse 
$ mvn clean install

Maven Dependency scope management

 Software dependency :
  - G: groupID
  - A: artifactID  
  - V: Version
  - Scope
    - compile   compile 、 function 、 test 、 pack ( Default )
    - provided  compile 、 function  eg: servlet
    - runtime   function 、 pack  eg: mysql
    - test      test 
    - system    compile 、 function 

Maven Parent child projects rely on passing

Father son project
advantage :

  1. Reasonable and effective reuse dependency jar package
  2. The subprojects are independent of each other , More convenient for agile development and independent management

shortcoming :

  1. The performance of system integration between projects is poor

Parent project pom.xml

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

<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>com.demo</groupId>
  <artifactId>maven-parent</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>maven-parent</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <!-- 1、 How the parent project is packaged  -->
  <packaging>pom</packaging>

  <!-- 2、 Unified version management  -->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <log4j.version>1.2.17</log4j.version>
    <junit.version>4.11</junit.version>
    <spring.version>5.1.9.RELEASE</spring.version>
  </properties>

  <!--3、 Basic dependencies in the parent project  -->
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>

  <!--4、 The dependency of unified management in the parent project , Rely on the container , Only when used in subprojects -->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

</project>

subprojects pom.xml

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

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

  <!--1、 Inheritance relationships , Inherit a project  -->
  <parent>
    <groupId>com.demo</groupId>
    <artifactId>maven-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../maven-parent/pom.xml</relativePath>
  </parent>

  <!--2、 In subprojects , Will automatically inherit the parent project groupId-->
  <!--<groupId>com.demo</groupId>-->
  <artifactId>maven-wiki</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>maven-wiki</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

  <!--  3、 Use in the parent project , Unified managed dependencies in the dependency manager -->
  <!--   Can not write version number , Unified management by the parent project  -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
  </dependencies>

</project>

Maven Project aggregation and unified management

Project aggregation relationships :
The integrity between projects is high , Easy for system integration and maintenance

<modules>
    <module>maven-child1</module>
    <module>maven-child2</module>
</modules>

Maven Plug-in management

Life cycle plug-ins

  • resources
  • source
  • clean
  • compile

Common operation plug-ins

  • tomcat7
  • dependency
  • jar

Maven Plug in search
https://maven.apache.org/plugins/index.html

View dependency plug-ins

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.1.2</version>
</plugin>

View dependencies

$ mvn dependency:tree

IDEA You can right-click to view the dependency graph

Maven Private server

  • Apache Archiva
  • JFrog Artifactory
  • Sonatype Nexus

The download page :
https://www.sonatype.com/nexus/repository-oss/download

Products->Nexus Repository Manager->OSS Edition

perhaps :
https://help.sonatype.com/repomanager3/download

Foreign address cannot be downloaded , Find a way , Use the server in Hong Kong to download and then download to local

Baidu online disk download :
link : https://pan.baidu.com/s/1HY3Cwr8KSCm92JByc_BmQg
Extraction code : 6jwk

operation

#  start-up 
cd bin
$ ./nexus start

Default port :
http://localhost:8081/

Create a private warehouse

Private server classification

  • proxy Agent remote warehouse
  • group Group management
  • hosted Launch local development projects
    • releases Stable version
    • snapshots Snapshot version

Rely on downloads and project releases

Depending on the search order :

 Local repository  <  Private warehouse  <  The central warehouse 

After logging in, you can create a new warehouse

1、 Download dependencies from private repositories through agents pom.xml

<!-- Configure private warehouse address -->
<!-- The cached packages will be downloaded from the private repository -->
<repositories>
    <repository>
        <id>my-central</id>
        <name>My Central</name>
        <url>http://localhost:8081/repository/my-central/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

2、 Publish the project pom.xml

<groupId>com.demo</groupId>
<artifactId>maven-demo</artifactId>

<!--  Snapshot version  -->
<version>1.0-SNAPSHOT</version>

<!--  Official version   -->
<version>1.0-RELEASE</version>


<!-- Configure the publishing warehouse address -->
<distributionManagement>
    <repository>
        <id>my-release</id>
        <name>My Release</name>
        <url>http://localhost:8081/repository/my-release/</url>
    </repository>

    <snapshotRepository>
        <id>my-snapshot</id>
        <name>My Snapshot</name>
        <url>http://localhost:8081/repository/my-snapshot/</url>
    </snapshotRepository>
</distributionManagement>

Configure account password ~/.m2/settings.xml

<servers>
    <server>
        <id>my-snapshot</id>
        <username>admin</username>
        <password>123456</password>
    </server>
    <server>
        <id>my-release</id>
        <username>admin</username>
        <password>123456</password>
    </server>
</servers>

Release

$ mvn deploy

Maven structure JavaSE project

adopt IDEA establish Maven project

Project structure

.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── demo
    │   │           └── HelloWorld.java
    │   └── resources
    └── test
        └── java

HelloWorld.java

package com.demo;

public class HelloWorld {
    
    public static void main(String[] args) {
    
        System.out.println("hello");
    }
}

Operation mode :

  1. Direct operation

  2. Configure operating parameters

exec:java -Dexec.mainClass="com.example.HelloWorld"

Maven structure JavaWeb project

Project skeleton :maven-archetype-webapp

Create... By hand

Project structure

.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── demo
    │   │           └── HelloServlet.java
    │   ├── resources
    │   └── webapp
    │       ├── WEB-INF
    │       │   └── web.xml
    │       └── index.jsp
    └── test
        └── java

pom.xml

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

<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>com.demo</groupId>
    <artifactId>java-web-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--  Modify the packing method  -->
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <!-- Compile and run time -->
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Command line start :$ mvn tomcat7:run-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1"
         metadata-complete="false">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
</head>
<body>
    <h2> my web project </h2>
</body>
</html>

HelloServlet.java

package com.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  Use  WebServlet  Need configuration  web.xml
 * version > 3.0
 * metadata-complete=false
 *
 *  Reference resources :https://www.cnblogs.com/iCheny/p/10976735.html
 */
@WebServlet(value = "/hello")
public class HelloServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        resp.getWriter().println("Hello World.");
    }
}

The project build Project Structure establish Web modular

Two ways to start :

1、 Command line run

$ mvn tomcat7:run

2、 To configure Tomcat

IDEA It's not very good to change or take effect , It's very painful to develop
Eclipse It took effect in a timely manner

With Debug mode , It will take effect after compilation

Dependency conflict

1、 Direct conflict of dependence

<dependency>
  <groupId>commons-beanutils</groupId>
  <artifactId>commons-beanutils</artifactId>
  <version>1.9.4</version>
</dependency>

<!--  Priority should be given to excluding low version dependencies , Generally, the higher version will be compatible with the lower version  -->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.5-FINAL</version>
  <exclusions>
    <exclusion>
      <artifactId>commons-logging</artifactId>
      <groupId>commons-logging</groupId>
    </exclusion>
  </exclusions>
</dependency>

2、 Dependency transitive conflict

Course summary

  1. Environment building , File structure

  2. The project build , Configuration carding

  3. Warehouse , coordinate , Command and life cycle

  4. Scope management of project dependencies

  5. The transmission of the father son project , Aggregate project management

  6. Private server building uses

  7. Plug in to enhance project functionality

  8. Construction of different types of projects

  9. Resolve dependency conflicts in the project

版权声明
本文为[Peng Shiyu]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224171911696g.html

Scroll to Top