如何在maven中添加jar依赖?

how to add jar dependency in maven?

当我运行

mvn compile

我得到 package com.ibm.icu.util does not exist。所以我下载了 ICU4J jar 并将其安装到本地存储库中。我确认它在 .m2/repository/com/ibm/icu/icu4j/3.4.4/icu4j-3.4.4.jar 中。在该 jar 文件中是丢失的 class 文件 com/ibm/icu/util/Calendar.class。然后我将以下内容添加到 pom.xml 的依赖项部分:

<dependency>
   <groupId>com.ibm.icu</groupId>
   <artifactId>icu4j</artifactId>
   <version>3.4.4</version>
</dependency>

但是当我再次 运行 mvn compile 时,我得到了同样的错误。我做错了什么?

您不应该手动将东西安装到 Maven 存储库目录中。该目录由maven自己维护。

依赖项的工作方式是,当您 运行 mvn compile 或其他目标时,它将连接到 Maven 中央存储库并下载所需的依赖项及其依赖项。

如果您手动安装一个 jar 文件,它可能没有它的依赖项。那个 icu 神器可能有它依赖的其他东西。 Maven 会自动解决这些依赖关系。

我建议使用 mvn clean install 这将清理目标目录并重建所有内容。

如果下载失败,那么您可能需要更改maven 配置。例如,如果您在代理服务器后面,则需要使用代理凭据配置 Maven。

此外,如果您手动将任何内容复制到 .m2/repository/ 目录中,您应该将其删除并让 maven 将其正确地放入其中。

maven 的美妙之处在于您无需担心下载 jar 之类的事情。它只是为你处理。让它完成它的工作。

如果您有像 JFrog 这样的内部工件,也许您应该检查 jar 是否在那里。不要手动下载到 .m2,因为它至少很奇怪。最多只能手动上传那个artifactory里面的jar。

您应该避免手动添加依赖项。

如果您不知道所需依赖项的 groupId 和 artifactId,请在 http://mvnrepository.com/ 中搜索。通常,groupId 与 jar 文件中的包名称匹配。

对于您的情况,依赖项已经存在:http://mvnrepository.com/search?q=com.ibm.icu 所以,去 http://mvnrepository.com/artifact/com.ibm.icu/icu4j and get the version of the dependency you need, e.g. 55.1: http://mvnrepository.com/artifact/com.ibm.icu/icu4j/55.1 获取 Maven 依赖项 xml 并将其放入您的 pom.xml 文件:

<dependency>
    <groupId>com.ibm.icu</groupId>
    <artifactId>icu4j</artifactId>
    <version>55.1</version>
</dependency>

如果您没有找到您的依赖项,请尝试在 google 中找到它。有时可能会在某些公司 public 存储库中找到依赖项,而不是在 pom.xml.

central. In this case you need to add the third-party repository to repositories section

如果您无法在 public 存储库中找到您的依赖项,那么您有以下三种选择:

A. 将 jar 安装到内部存储库服务器(例如 nexus)

B. 将 JAR 文件放入项目源中 declare project maven repository :

<repositories>
    <repository>
        <id>my-local-repo</id>
        <url>file://${basedir}/my-repo</url>
    </repository>
</repositories>

重要提示:您应该将 maven repository layout 保存在本地存储库中。

C。 [错误做法] 使用 maven install plugin 将自定义 jar 安装到计算机上的本地存储库。但是不好用,不推荐

mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file -Dfile=path-to-your-artifact-jar -DpomFile=path-to-pom

D. [错误做法]system dependency 与 JAR 文件的 绝对 路径一起使用,尽管这是一种错误做法,应该避免。

<dependency>
  <groupId>test</groupId>
  <artifactId>test</artifactId>
  <version>X.Y.Z</version>
  <scope>system</scope>
  <systemPath>${user.home}/jars/my.jar</systemPath>
</dependency>