简体   繁体   中英

Avoiding cyclic dependencies in Maven

I have a project A that has project B listed as a dependency, but B does not have A as a dependency. I want to use classes from A inside B without creating a cyclic dependency. What's the best way to accomplish this without creating a new project?

A brute force approach that I thought of was to just obviously copy and paste the classes I need from A to B but this is clearly bad.

I have a project A that has project B listed as a dependency, but B does not have A as a dependency.

If A depends on B, then B cannot depend on A.

Note cyclic dependencies are problematic even if you don't use Maven. It breaks when you start use Java 8+ modules too. And you can run into build stability / convergence issues without using modules.

I want to use classes from A inside B without creating a cyclic dependency.

Move the classes from B to A. (Don't copy them. You don't want the same class in two places. If the fully qualified names are different you have duplicated code. If they are the same, you could also run into runtime problems.)

Alternatively, create a third project C to contain the classes and have A and B depend on C.

Alternatively, combine A and B into a single project.

Alternatively, refactor the classes themselves; eg to introduce interfaces or abstract classes at the appropriate point, or move methods / functionality around.

In short, there are many ways to avoid a cyclic dependency between projects. You just need to analyze your code to work out the most appropriate way (or ways) to do it. There is no magic formula / "best practice". Just hard work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM