How to get the list of all the beans in your spring boot application?

Spring Boot stores all managed objects inside the ApplicationContext, which acts as the Spring IoC container. To retrieve all registered beans, we can use the getBeanDefinitionNames() method provided by the ApplicationContext interface.

Key Points: • ApplicationContext maintains all Spring-managed beans in the application. • The getBeanDefinitionNames() method returns the names of all registered beans. • This approach is useful for debugging, troubleshooting, and understanding the application context.

Example: Suppose an application contains the following beans:

• UserService • UserRepository • EmailService • PaymentService

Using ApplicationContext, we can retrieve and print all these bean names at runtime.

Code Example:

@Component
public class BeanPrinter {

    @Autowired
    private ApplicationContext applicationContext;

    public void printBeans() {

        String[] beans =
                applicationContext.getBeanDefinitionNames();

        Arrays.sort(beans);

        for (String bean : beans) {
            System.out.println(bean);
        }
    }
}

Alternative Approach:

@Component
public class BeanPrinter
        implements CommandLineRunner {

    @Autowired
    private ApplicationContext context;

    @Override
    public void run(String... args) {

        String[] beans =
                context.getBeanDefinitionNames();

        for (String bean : beans) {
            System.out.println(bean);
        }
    }
}

This prints all beans automatically during application startup.

Common Use Cases:

• Debugging bean creation issues. • Verifying component scanning. • Troubleshooting auto-configuration problems. • Understanding application startup behavior.

Spring Boot Actuator Alternative:

The following endpoint can also expose bean information:

/actuator/beans

This provides detailed information about all loaded beans and their dependencies.

Interview Tip: A concise interview answer is: To get the list of all beans in a Spring Boot application, I would inject the ApplicationContext and call the getBeanDefinitionNames() method. This returns all bean names registered in the Spring container and is commonly used for debugging and application analysis.