Resolve circular dependency in gradle

狂风中的少年 提交于 2020-01-14 05:42:09

问题


I recently started developing a java project which has some sub projects within it. All of them are gradle. So let's say there are two projects A and B which is already implemented. And I'm going to introduce another graldle project C. And the dependencies are like this.

  • A has dependencies on B
  • B has dependencies on C
  • C has dependencies on A

So I need to implement this project C without cyclic dependencies error as it is given when I tried to build the project with gradle. I saw some answers that Interface is a solution for this. But in my case project A and B are large projects and I can't event think how to introduce a Interface for them. Only thing I can do is introducing interfaces for project C. So is there a way to solve my problem with these cases? If there isn't what is the way to have such an one? And please note that these A,B,C projects are individual projects so those can't combine as one.


回答1:


Foreword

There is no magic that will let you compile your project when there's a cycle in your dependency graph. You'll need to do some refactoring to eliminate the cycle.

The way you deal with circular dependencies is split the modules to smaller ones and repeat that until you have eliminated the cycle.

Algorithm

1) 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. If it does you need to continue splitting.

2) Let's say D stil depends on B:

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 <--

Once again if E has no dependencies causing a cycle - you're done. If not - continue.

3) Let's say E stil depends on C:

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

What do we do? Obvioulsy split C (extract F):

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

Afterword

Note that it might not be that easy if at all doable (within a sane amount of time and/or budget), so given the context it might be preferable to just duplicate the code in A that C relies on.



来源:https://stackoverflow.com/questions/58178381/resolve-circular-dependency-in-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!