Forem

Query Filter
Query Filter

Posted on

bridge111

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");
        dot.append("  rankdir=LR; nodesep=0.5; ranksep=1.5; splines=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()) {
                    // Filter out noise
                    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=<");
                            // CELLPADDING=4 provides the internal margin needed to stop text overflow
                            dot.append("<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\" BGCOLOR=\"").append(color).append("\">");

                            // FIXED HEADER: Added internal padding and fixed width hint to prevent overflow
                            dot.append("<TR><TD BGCOLOR=\"#999999\" ALIGN=\"CENTER\"><B>").append(xmlEscape(name)).append("</B></TD></TR>");

                            for (PropertyValue pv : def.getPropertyValues().getPropertyValues()) {
                                dot.append("<TR><TD ALIGN=\"LEFT\">");
                                dot.append("<B>").append(xmlEscape(pv.getName())).append(":</B> ");
                                dot.append(extractValue(pv.getValue(), 0));
                                dot.append("</TD></TR>");
                            }
                            dot.append("</TABLE>>];\n");

                            // Connections
                            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("&", "&amp;")
                    .replace("<", "&lt;")
                    .replace(">", "&gt;")
                    .replace("\"", "&quot;")
                    .replace("'", "&apos;")
                    .replace("&lt;BR ALIGN=&quot;LEFT&quot;/&gt;", "<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(); }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)