默认情况下可以使用什么范围使依赖关系不可传递?

What scope can be used to make a dependency non-transitive by default?

如果我想让项目 A 编译并测试 运行,但是当我将它作为依赖项放入项目 B 时,项目 A 的依赖项应该不适用于项目 B.

例如:

  1. org.example.foo 作为依赖项添加到项目 A(不是 B

  2. 将项目 A 添加为项目 B 中的依赖项

  3. 在项目 B 中的 class 中添加此语句:import org.example.foo.*

  4. 你应该在这一行得到一个编译错误:import org.example.foo.*

您可以通过这样的排除来排除特定的传递依赖:

<project>
  ...
  <dependencies>
    <dependency>
      <groupId>sample.ProjectA</groupId>
      <artifactId>Project-A</artifactId>
      <version>1.0</version>
      <exclusions>
        <exclusion>  <!-- declare the exclusion here -->
          <groupId>sample.ProjectB</groupId>
          <artifactId>Project-B</artifactId>
        </exclusion>
      </exclusions> 
    </dependency>
  </dependencies>
</project>

或者您可以像这样排除所有传递依赖(需要 Maven 3.2.1+):

<project>
  ...
  <dependencies>
    <dependency>
      <groupId>sample.ProjectA</groupId>
      <artifactId>Project-A</artifactId>
      <version>1.0</version>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions> 
    </dependency>
  </dependencies>
</project>

除此之外,如果您可能需要更改项目 A 以使用不同的依赖项等,我会认真考虑您的项目结构。

对于Gradle,你可以使用gradle-dependency-analyze插件,它会添加analyzeClassesDependencies任务:

This task depends on the classes task and analyzes the dependencies of the main source set's output directory. This ensures that all dependencies of the classes are declared in the compile, compileOnly, or provided configuration. It also ensures the inverse, that all of the dependencies of these configurations are used by classes

所以它不会触发编译问题,但如果 B 尝试导入 org.example.foo.*,在 B 的构建过程中你会收到此消息:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':B:analyzeClassesDependencies'.
> Dependency analysis found issues: usedUndeclaredArtifacts: 
   - org.example.foo:foo-core:1.0.0

要么 B 需要它自己的 foo-core 依赖项(它不能使用 A 的),要么不允许并且 A 的依赖项仍然不可用(无法构建)

这里gradle-dependency-analyze plugin mentioned in this 的自述文件提到:

This plugin attempts to replicate the functionality of the maven dependency plugin's analyze goals which fail the build if dependencies are declared but not used or used but not declared.

以此为主导,当我检查了 maven 依赖插件的 dependency:analyze goal, I found the option failOnWarning,这可能就是你所追求的。

因此,您可以像这样将它插入项目 B 的 Maven 调用:

mvn -DfailOnWarning=true dependency:analyze < other goals e.g. package >

并且,如果有任何 Used undeclared dependenciesUnused declared dependencies 的实例,前者是您的用例,构建将失败。

唯一的缺点是,我没有找到任何 command-line 方法让插件忽略 Unused declared dependencies

您应该使用 <scope>provided</scope> 指定项目 "A" 中的依赖项。这样各自的依赖被用于编译和测试,但在项目"B".

中不被传递使用

在这里您可以找到 Maven 依赖项的不同范围:https://maven.apache.org/pom.html#Dependencies