解决Gradle中的循环依赖问题

6

我最近开始开发一个Java项目,其中包含一些子项目。它们都是gradle项目。假设已经实现了两个项目A和B,我要引入另一个gradle项目C,并且依赖关系如下:

  • A依赖于B
  • B依赖于C
  • C依赖于A

因此,我需要在不出现循环依赖错误的情况下实现项目C,当我使用gradle构建该项目时会出现此错误。我看到有些答案说接口是解决方案。但在我的情况下,A和B是大型项目,我甚至不知道如何为它们引入接口。唯一能做的就是为项目C引入接口。那么有没有办法用这些方法解决我的问题?如果没有,有什么方法可以解决这个问题?请注意,这些A、B、C项目是独立的项目,不能合并成一个项目。


你可能想看一下这个答案 - Mushif Ali Nawaz
当我使用它配置gradle时,我无法进入项目文件。源目录的内容显示为空,但实际上并不为空。 - Shehan Dhaleesha
1个回答

11

前言

当你的依赖关系图中存在循环依赖时,没有什么神奇的方法可以让你编译项目。你需要进行一些重构来消除这种循环依赖。

处理循环依赖的方法是拆分模块并重复该过程,直到循环依赖被消除(或使用下面提供的替代方法)。

算法

  1. Starting point:

    A --> B --> C
    ^           |
    |           |
    +-----------+
    
  2. Start with extracting the parts of A that are used by C to a separate module (let's call it D):

    A --> B --> C
    |           |
    |           |
    +---> D <---+
    

    If D does not depend on any other module you're done. Otherwise continue cutting the cords.

  3. Let's say D stil has a B dependency:

    A --> B --> C
    |     ^     |
    |     |     |
    +---> D <---+
    

    You need to analogically extract common parts from B (to let's call it E):

    A --> B --> C
    |     |     |
    |     v     |
    |     E     |
    |     ^     |
    |     |     |
    +---> D <---+
    

    Just like before - repeat if E still has problematic dependencies.

  4. Let's say E stil depends on C:

    A --> B --> C --+
    |     |     ^   |
    |     v     |   |
    |     E ----+   |
    |     ^         |
    |     |         |
    +---> D <-------+
    

    What do we do? Obvioulsy split C (by extracting F):

    A --> B --> C --+
    |     |     |   |
    |     v     v   |
    |     E --> F   |
    |     ^         |
    |     |         |
    +---> D <-------+
    
  5. Continue the loop until a point is reached where the newly introduced module has no more dependecies in the module graph.

    For example in point 3) we're done if we assume that F is dependencyless. This means that the problematic part of A used by C has been extracted to the D ─► E ─► F subgraph.

备选方案

请注意,在合理的预算范围内,实现此方案可能并不容易,甚至可能无法实现。因此,在某些情况下,最好采用次优方案:复制代码 AC所依赖的部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接