Avoid circular dependencies in gradle build

2019-08-02 16:20发布

问题:

My Java project is setup like this:

ProjectRoot ModuleA src main java ModuleB src main java ModuleC src main java

ModuleC is used to hold code that is common to both ModuleA and ModuleB. However, ModuleC also has code that references code in ModuleA and ModuleB. In effect, this is a circular reference. Note however, that when ModuleC does call APIs in ModuleA or ModuleB, no circular calls are actually made since the APIs themselves do not call anything in ModuleC. My gradle project fails because the code in ModuleC cannot resolve the dependencies for ModuleA and ModuleB.

For ModuleA the settings.gradle file look like this:

include 'ModuleA', ":ModuleC" project(':ModuleC').projectDir = new File('../ModuleC')

For ModuleB the settings.gradle file look like this:

include 'ModuleB', ":ModuleC" project(':ModuleC').projectDir = new File('../ModuleC')

In the build.gradle files for ModuleA and ModuleB I set the dependencies to:

dependencies { compile project(':ModuleC') }

But I cannot put this into ModuleC because it will create a circular dependency:

dependencies { compile project(':ModuleA') compile project(':ModuleC')

So what settings do I need to make to avoid circular dependencies?

回答1:

According to this post, it is not possible:

https://stackoverflow.com/a/38063421/753632

However, I came up with a solution whereby you don't reference dependencies but instead treat ModuleC as the main project and then include the source code from the other modules. So in the build.gradle file for ModuleC:

sourceSets { main { java { srcDirs 'src' srcDirs '../ModuleA/src' srcDirs '../ModuleB/src' } } }

Then to build the project, open a terminal only in ModuleC's folder and run gradle build



标签: gradle