package com.yourpackage;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.SmartLifecycle;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
public class SpringVisualizer implements ApplicationContextAware, SmartLifecycle {
private ConfigurableApplicationContext context;
private boolean isRunning = false;
private final Set<String> currentBeanManualDeps = new HashSet<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.context = (ConfigurableApplicationContext) applicationContext;
}
@Override
public void start() {
StringBuilder dot = new StringBuilder("digraph G {\n");
// newrank helps with large graphs; nodesep adds breathing room between boxes
dot.append(" rankdir=LR; nodesep=1.0; ranksep=2.0; splines=true; newrank=true;\n");
dot.append(" node [shape=none, fontname=\"Verdana\", fontsize=10];\n");
dot.append(" edge [fontname=\"Verdana\", fontsize=8, color=\"#666666\"];\n\n");
Set<String> processed = new HashSet<>();
int count = 0;
ApplicationContext currentCtx = this.context;
while (currentCtx != null) {
if (currentCtx instanceof ConfigurableApplicationContext) {
ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) currentCtx).getBeanFactory();
for (String name : factory.getBeanDefinitionNames()) {
if (name.startsWith("org.springframework")) continue;
if (processed.add(name)) {
try {
BeanDefinition def = factory.getBeanDefinition(name);
currentBeanManualDeps.clear();
count++;
String color = name.toLowerCase().contains("comet") ? "#FFF9C4" :
(name.toLowerCase().contains("cpls") ? "#C8E6C9" : "#E1F5FE");
dot.append(" \"").append(name).append("\" [label=<");
// Using CELLSPACING=0 and a 2-column layout to prevent overstrike
dot.append("<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"6\" BGCOLOR=\"").append(color).append("\">");
// HEADER: COLSPAN=2 ensures the header stretches the whole table width
dot.append("<TR><TD COLSPAN=\"2\" BGCOLOR=\"#999999\" ALIGN=\"CENTER\"><B>").append(xmlEscape(name)).append("</B></TD></TR>");
for (PropertyValue pv : def.getPropertyValues().getPropertyValues()) {
dot.append("<TR>");
dot.append("<TD ALIGN=\"LEFT\"><B>").append(xmlEscape(pv.getName())).append("</B></TD>");
dot.append("<TD ALIGN=\"LEFT\">").append(extractValue(pv.getValue(), 0)).append("</TD>");
dot.append("</TR>");
}
dot.append("</TABLE>>];\n");
Set<String> allDeps = new HashSet<>(Arrays.asList(factory.getDependenciesForBean(name)));
allDeps.addAll(currentBeanManualDeps);
for (String dep : allDeps) {
if (!dep.startsWith("org.springframework")) {
dot.append(" \"").append(name).append("\" -> \"").append(dep).append("\";\n");
}
}
} catch (Exception ignored) {}
}
}
}
currentCtx = currentCtx.getParent();
}
dot.append("}\n");
writeToFile(dot.toString());
this.isRunning = true;
}
private String extractValue(Object value, int depth) {
if (value == null) return "null";
if (depth > 3) return "[...]";
if (value instanceof BeanReference) {
String bName = ((BeanReference) value).getBeanName();
currentBeanManualDeps.add(bName);
return "@" + xmlEscape(bName);
}
if (value instanceof TypedStringValue) {
return xmlEscape(((TypedStringValue) value).getValue());
}
if (value instanceof Iterable) {
StringBuilder sb = new StringBuilder();
for (Object item : (Iterable<?>) value) {
sb.append(extractValue(item, depth + 1)).append("<BR ALIGN=\"LEFT\"/>");
}
return sb.toString();
}
if (value instanceof Map) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> e : ((Map<?, ?>) value).entrySet()) {
sb.append(extractValue(e.getKey(), depth + 1)).append("=").append(extractValue(e.getValue(), depth + 1)).append("<BR ALIGN=\"LEFT\"/>");
}
return sb.toString();
}
return xmlEscape(value.toString());
}
private String xmlEscape(String input) {
if (input == null) return "";
return input.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'")
.replace("<BR ALIGN="LEFT"/>", "<BR ALIGN=\"LEFT\"/>");
}
private void writeToFile(String content) {
try {
File current = new File(System.getProperty("user.dir"));
File buildDir = new File(current, "build");
if (!buildDir.exists()) buildDir.mkdirs();
File file = new File(buildDir, "spring-beans.dot");
try (FileWriter writer = new FileWriter(file)) {
writer.write(content);
}
System.err.println("File URL: " + file.toURI().toString());
} catch (Exception e) { e.printStackTrace(); }
}
@Override public int getPhase() { return Integer.MAX_VALUE; }
@Override public boolean isAutoStartup() { return true; }
@Override public void stop() { this.isRunning = false; }
@Override public boolean isRunning() { return this.isRunning; }
@Override public void stop(Runnable callback) { stop(); callback.run(); }
}
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)