How can I get to know names of all the beans that are loaded as part of my spring boot app? I would like have some code in main method to print the details of beans that are loaded once the server is started up.
In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.
The ListableBeanFactory interface provides getBeanDefinitionNames() method which returns the names of all the beans defined in this factory. This interface is implemented by all the bean factories that pre-loads their bean definitions to enumerate all their bean instances.
The beans in Spring are stored in an IoC (Inversion of Control) container which is often referred as Application Context.
As shown in the getting started guide of spring-boot: https://spring.io/guides/gs/spring-boot/
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } }; } }
As @Velu mentioned in the comments, this will not list manually registered beans.
In case you want to do so, you can use getSingletonNames(). But be careful. This method only returns already instantiated beans. If a bean isn't already instantiated, it will not be returned by getSingletonNames()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With