Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve cyclic dependency in Maven?

How can we resolve a Maven cyclic dependency?

Suppose A is the parent project and B and C are child projects. If B is dependent on C and C is dependent on B, is there any way to resolve the cyclic dependency other than having a different project.

like image 817
user2367460 Avatar asked May 09 '13 18:05

user2367460


People also ask

How do you fix cyclic dependency?

There are a couple of options to get rid of circular dependencies. For a longer chain, A -> B -> C -> D -> A , if one of the references is removed (for instance, the D -> A reference), the cyclic reference pattern is broken, as well. For simpler patterns, such as A -> B -> A , refactoring may be necessary.

How do you solve cyclic dependency in Java?

A simple way to break the cycle is by telling Spring to initialize one of the beans lazily. So, instead of fully initializing the bean, it will create a proxy to inject it into the other bean. The injected bean will only be fully created when it's first needed.


2 Answers

Maven does not allow cyclic dependencies between projects, because otherwise it is not clear which project to build first. So you need to get rid of this cycle. One solution is the one you already mentioned, to create another project. Another one would be to just move some classes from B to C or vice versa when this helps. Or sometimes it is correct to merge project B and C to one project if there is no need to have two of them.

But without knowing and analyzing why your projects depend on each other it's kinda difficult to suggest the best solution.

So I suggest you can use tools like JDepend or the InteliJ analyse tool to find your problematic classes and based on them find a better design for your software.

Most of the time, I create something like an interface module and and implementation module, which gets rid of most cycles. Check out the answer from Dormouse in this thread and search for Dependency Inversion Principle to get more sources on this topic.

like image 181
mszalbach Avatar answered Sep 19 '22 10:09

mszalbach


Creating a new project is indeed one solution.

Dependency Inversion is the second possible solution.

Refer to here for the Acyclic Dependency Principle.

And here for the Dependency Inversion Principle.

like image 22
Dormouse Avatar answered Sep 19 '22 10:09

Dormouse