java - 为什么我需要添加 Artifact JSR305 才能使用 Guava 14+?

标签 java maven guava jsr305

在查找有关stackoverflow 的信息时,我看到了一个与我类似的问题,但没有真正的答案here .

我需要将我的 Maven 项目从 guava 11.0.2 迁移到 guava 14 或更高版本(我需要 RangeSet)。我用依赖项更新了我的 maven pom:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>14.0</version>
</dependency>

然后我运行 maven 构建,并得到这个错误:

[ERROR] xxx.java: cannot find symbol
[ERROR] symbol  : class Nonnull
[ERROR] location: package javax.annotation

仔细一看,这个注解是JSR305自带的,依赖guava 11.0.2,如mvn repository报告它。

我觉得奇怪的是 guava 14 也依赖于 JSR305 作为 mvn repository报告。

如果我将 JSR 依赖项添加到我的 pom,那么编译就可以正常运行:

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>1.3.9</version>
    <scope>provided</scope>
</dependency>

但是如果 guava 已经依赖它,为什么我还必须将这个依赖添加到我的 pom 中呢?这看起来更像是一种解决方法而不是解决方案,我更愿意理解并使事情变得干净。

感谢参与。

最佳答案

之所以需要添加它作为依赖是因为Guava 14在他们的pom中定义了如下依赖:

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>1.3.9</version>
    <scope>provided</scope>
</dependency>

您的问题的重要部分是 <scope>provided</scope>线。

来自 maven website他们就 provided 陈述了以下内容依赖项:

provided: This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

所以基本上是因为 Guava 将其设置为 provided他们期望使用 Guava 的任何人提供这种依赖性,而这正是您必须做的。

在 Guava 11.0.2 中它是一个正常的 compile依赖项,因此您不必在自己的项目中提供它。

更改是在 Guava 13 中进行的。来自 release notes :

Made findbugs a provided dependency to avert dep conflicts when using findbugs 2.0. The side-effect of this change is that projects which relied upon Guava to grant access to the JSR-305 annotations "for free" will break unless they provide their own direct dependency on that jar (or an equivalent). Projects should always have been directly depending on JSR-305 (per maven best-practice), but this change makes that should into a must.

关于java - 为什么我需要添加 Artifact JSR305 才能使用 Guava 14+?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263673/

相关文章:

java - Guava 为什么 toStringFunction 不是泛型函数?

java - 在 Java 文件中创建时,表列分布不均匀

java - 如何使用 Maven Enforcer 插件?

java - 使用 Maven 在 Java 8 中找不到适合 jdbc 的驱动程序

java - 如何使用TypeToken获取类型参数?

java - Guava map 中驱逐的懒惰

java - 以编程方式交换 JFrame 中的两个 JPanel

java - 查询 LDAP 结构未知的 LDAP 服务器

Java 信任库在生产环境中不起作用

scala - 构建 maven 项目作为 SBT 构建的一部分