Skip to content

Instantly share code, notes, and snippets.

Last active Nov 28, 2018
What would you like to do?
Spring Circular Dependency Analysis
public class DepGraph {
private final Map<String, Set<String>> nodes;
private DepGraph(Map<String, Set<String>> nodes) {
this.nodes = nodes;
public Set<String> calculateCycles() {
Set<String> visited = new HashSet<>();
return nodes.keySet().stream()
.map(node -> calculateCycles(node, visited, Collections.emptyList()))
private Set<String> calculateCycles(String node, Set<String> visited, List<String> path) {
List<String> newPath = new LinkedList<>(path);
if (path.contains(node)) {
List<String> cycle = newPath.subList(path.indexOf(node), path.size());
return Collections.singleton(String.join("->", cycle));
if (visited.contains(node)) {
return Collections.emptySet();
Set<String> deps = nodes.getOrDefault(node, Collections.emptySet());
.map(dep -> calculateCycles(dep, visited, newPath))
public static DepGraph buildDependencyGraph(GenericApplicationContext applicationContext) {
ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory();
Map<String, Set<String>> beanDeps =
.filter(beanName -> !factory.getBeanDefinition(beanName).isAbstract())
beanName -> new HashSet<>(Arrays.asList(factory.getDependenciesForBean(beanName)))
return new DepGraph(beanDeps);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment