一、Maven概述

Maven是Apache开源基金会旗下孵化的一个包管理器,在java开发中有着广泛的应用。java开发者开发了大量的jar包形成了java开发的生态。和Python的pip和conda一样,maven负责安装与管理这些第三方库。

maven安装

比较容易,主要是以下几步

  • 官网下载
  • 解压到你的安装目录(即为免安装版本)
  • 配置该安装目录为MAVEN_HOME环境变量
  • 同时将%MAVEN_HOME%\bin追加到PATH环境变量,如果是Linux,则为$MAVEN_HOME/bin

maven配置

maven是基于XML进行配置的,主要有三个层面的配置,后续配置会覆盖前面的相同配置。其中settings.xml主要用来配置本地仓库、远程仓库、仓库镜像等。pom.xml则配置了当前项目所有的依赖等信息。

  • 全局配置$MAVEN_HOME/conf/settings.xml
  • 用户配置~/.m2/settings.xml
  • 项目配置./pom.xml

依赖下载

通过mvn install能够下载当前仓库所需的所有依赖。

仓库配置

本地仓库位置自定义

本地仓库默认位置是当前用户~/.m2/repository,但有时候该目录的硬盘容量不能满足需求,因此可以自定义,可以在settings.xml中设置顶级标签localRepository。建议是在用户配置中设置,不用全局修改。

1
2
<?xml version="1.0" encoding="UTF-8"?>
<localRepository>Your local repository path</localRepository>

添加远程多个仓库

maven默认只有公共仓库(public)和中央仓库(central)等,但是初次之外还有很多第三方仓库(注意不是镜像)提供自己的jar包,因此maven中支持从多个仓库中搜索依赖。用户只需要在当前项目pom.xmlrepositories标签下配置多个repository即可。

1
2
3
4
5
6
7
8
9
10
<?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">
<repositories>
<repository>
<id>ebi-repo</id>
<name>ebi-repo</name>
<url>http://www.ebi.ac.uk/~maven/m2repo</url>
</repository>
</repositories>
</project>

如果是管理员,认为有必要全局添加第三方,可以在settings.xml中设置一个新的profile,然后在里面自定义仓库,记得把中央仓库也加入。例如下面是添加github的maven仓库。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<activeProfiles>
<activeProfile>github</activeProfile>
</activeProfiles>

<profiles>
<profile>
<id>github</id>
<repositories>
<repository>
<id>central</id>
<url>https://repo1.maven.org/maven2</url>
</repository>
<repository>
<id>github</id>
<url>https://maven.pkg.github.com/gcs-zhn/ddddocr-for-java</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</profile>
</profiles>

值得一提的是,github提供的仓库要求用户验证github账号,换言之你需要先注册github账号才能下载别人的maven公开包,并创建一个可以读写package的token,将其配置settings.xml如下,OWNER即为用户名,必须是小写,即使你注册的用户名是大写。TOKEN为github创建的token。这个账号和你想要使用的目标仓库无关,是你自己的github仓库。id前面仓库一致。
1
2
3
4
5
6
7
<servers>
<server>
<id>github</id>
<username>OWNER</username>
<password>TOKEN</password>
</server>
</servers>

镜像配置

在国内使用maven的仓库下载速度会很慢。所谓镜像是一个仓库的克隆,当配置指定仓库的镜像时,发往该仓库的请求会被拦截转发给镜像仓库,从而提高下载速度。可以在settings.xml中配置mirrors标签。其中mirrorOf是原始仓库的id,例如central和public,而url则是镜像地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<mirrors>
<mirror>
<id>aliyunmaven_center</id>
<mirrorOf>central</mirrorOf>
<name>阿里云中央仓库</name>
<url>https://maven.aliyun.com/repository/central</url>
</mirror>
<mirror>
<id>aliyunmaven</id>
<mirrorOf>public</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
</mirrors>