DEV Community

Query Filter
Query Filter

Posted on

Find bean in context

import java.lang.reflect.Method;
import java.util.Arrays;

public class SpringContextInspector {

// Get the Spring context from your custom ApplicationContext.getInstance()
public static org.springframework.context.ApplicationContext getSpringContext() {
    try {
        // Load your class (the one that has getInstance())
        Class<?> customCtxClass = Class.forName("ApplicationContext"); // If it's in the default package

        // Call static getInstance() method
        Method getInstanceMethod = customCtxClass.getMethod("getInstance");
        Object instance = getInstanceMethod.invoke(null);

        if (instance instanceof org.springframework.context.ApplicationContext) {
            return (org.springframework.context.ApplicationContext) instance;
        } else {
            System.err.println("getInstance() did not return a Spring ApplicationContext");
        }
    } catch (Exception e) {
        System.err.println("Error accessing ApplicationContext.getInstance(): " + e.getMessage());
    }
    return null;
}

// List all beans
public static void listAllBeans(org.springframework.context.ApplicationContext ctx) {
    if (ctx == null) {
        System.err.println("ApplicationContext is null.");
        return;
    }

    String[] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);

    System.out.println("=== Spring Beans ===");
    for (String name : beanNames) {
        try {
            Object bean = ctx.getBean(name);
            System.out.printf("%s -> %s%n", name, bean.getClass().getName());
        } catch (Exception e) {
            System.err.printf("Could not access bean '%s': %s%n", name, e.getMessage());
        }
    }
}

// Find one bean by name
public static void findBeanByName(org.springframework.context.ApplicationContext ctx, String beanName) {
    if (ctx == null) {
        System.err.println("ApplicationContext is null.");
        return;
    }

    if (ctx.containsBean(beanName)) {
        Object bean = ctx.getBean(beanName);
        System.out.println("✅ Found bean: " + beanName);
        System.out.println("Class: " + bean.getClass().getName());
        System.out.println("ToString: " + bean);
    } else {
        System.out.println("❌ Bean not found: " + beanName);
    }
}

// Main entry
public static void main(String[] args) {
    org.springframework.context.ApplicationContext ctx = getSpringContext();

    if (ctx == null) {
        System.err.println("Unable to get Spring ApplicationContext.");
        return;
    }

    if (args.length == 0) {
        listAllBeans(ctx);
    } else {
        findBeanByName(ctx, args[0]);
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)