Spring Boot – Print All Beans Loaded into Context

Spring boot initializes a lot of beans as part of autoconfiguration. We can find out all such beans loaded into application context in a spring boot application using getBeanDefinitionNames() method of ApplicationContext.

This information may be useful while customizing or overriding some of the bean definitions, or simply finding out the reason for any unwanted behavior in the application.

1. Printing All Beans

  • Spring’s CommandLineRunner class runs immediately after the application has been started fully. We can use it to print all loaded beans into the ApplicationContext.
  • Inside run() method, use ApplicationContext.getBeanDefinitionNames() to get the list of all loaded beans in runtime and print them in the output.
import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner run(ApplicationContext appContext) {
return args -> {

String[] beans = appContext.getBeanDefinitionNames();
Arrays.stream(beans).sorted().forEach(System.out::println);
};
}
}

Happy Learning !!

1 thought on “Spring Boot – Print All Beans Loaded into Context”

Leave a Comment