某些场景下,我们可能有一个依赖 Jar,但无法通过 Maven 仓库获取。这时,我们需要额外的配置来使用这个本地依赖, 以下是几种解决思路:

我们以本地 my-lib.jar 文件为例。

注册到 Maven 仓库

如果你使用的 Maven 仓库可以自己控制,如本地 Maven 仓库、自建的 Nexus,或者你有权限的其他仓库,你可以使用该方法,将本地 Jar 注册到仓库中, 后续可随时进行引用。

注册到本地仓库

创建 pom 文件 (可选) (推荐)

pom 文件是可选的,但是推荐使用。

xml
pom.xml
1
2
3
4
5
6
7
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>  <!-- 替换为您的组织名 -->
    <artifactId>my-artifact</artifactId>  <!-- 替换为您的项目名 -->
    <version>1.0.0</version>  <!-- 替换为版本号 -->
    <packaging>jar</packaging>
</project>

注册

完整命令格式如下:

shell
1
2
3
4
5
6
7
mvn install:install-file \
  -Dfile=<path-to-your-jar> \
  -DgroupId=<group-id> \
  -DartifactId=<artifact-id> \
  -Dversion=<version> \
  -Dpackaging=jar \
  -DgeneratePom=true  # 如果无 POM 文件,则自动生成

示例(以 my-lib.jar 为例):

  • 如果未定义 pom 文件,可使用如下命令:
shell
1
mvn install:install-file -Dfile=my-lib.jar -DgroupId=com.example -DartifactId=my-artifact -Dversion=1.0.0 -Dpackaging=jar -DgeneratePom=true
  • 如果定义了 pom 文件,则使用如下命令:
shell
1
mvn install:install-file -Dfile=my-lib.jar -DpomFile=pom.xml

推送到远程仓库

若要推送到远程仓库,首先需在 Maven 的 settings.xml 中配置远程仓库的认证信息。

远程仓库认证

xml
~/.m2/settings.xml
1
2
3
4
5
6
7
8
9
<settings>
  <servers>
    <server>
      <id>my-remote-repo</id>  <!-- 自定义 ID,需与 deploy 命令中的 repositoryId 匹配 -->
      <username>YOUR_USERNAME</username>  <!-- 替换为远程仓库用户名 -->
      <password>YOUR_PASSWORD</password>  <!-- 替换为密码 -->
    </server>
  </servers>
</settings>

推送

完整命令格式如下:

shell
1
2
3
4
5
6
7
8
mvn deploy:deploy-file \
  -Dfile=<path-to-your-jar> \
  -DgroupId=<group-id> \
  -DartifactId=<artifact-id> \
  -Dversion=<version> \
  -Dpackaging=jar \
  -Durl=<remote-repository-url> \  # 远程仓库 URL
  -DrepositoryId=<repository-id>  # 匹配 settings.xml 中的 <id>

示例(以 my-lib.jar 为例,推送到自定义 nexus 仓库):

  • 如果未定义 pom 文件,可使用如下命令:
shell
1
2
3
4
5
6
7
8
mvn deploy:deploy-file \
  -Dfile=my-lib.jar \
  -DgroupId=com.example \
  -DartifactId=my-artifact \
  -Dversion=1.0.0 \
  -Dpackaging=jar \
  -Durl=http://nexus.example.com/repository/maven-releases/ \
  -DrepositoryId=my-remote-repo
  • 如果定义了 pom 文件,则使用如下命令:
shell
1
2
3
4
5
mvn deploy:deploy-file \
  -Dfile=my-lib.jar \
  -DpomFile=pom.xml \  # 推荐使用现有 POM 文件
  -Durl=http://nexus.example.com/repository/maven-releases/ \  
  -DrepositoryId=my-remote-repo

自动化脚本

bash
install-and-deploy.sh
1
2
mvn install:install-file -Dfile=$1 -DgroupId=$2 -DartifactId=$3 -Dversion=$4 -Dpackaging=jar -DgeneratePom=true
mvn deploy:deploy-file -Dfile=$1 -DgroupId=$2 -DartifactId=$3 -Dversion=$4 -Dpackaging=jar -Durl=$5 -DrepositoryId=$6

示例代码:

shell
1
./install-and-deploy.sh my-lib.jar com.example my-artifact 1.0.0 http://repo-url my-remote-repo