Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all the Spring beans that are loaded - Spring Boot

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.

like image 861
Punter Vicky Avatar asked Oct 26 '15 14:10

Punter Vicky


People also ask

How do I get all beans in Spring boot?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.

Which method is used to get the names of all loaded beans in context?

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.

Where are beans stored in Spring boot?

The beans in Spring are stored in an IoC (Inversion of Control) container which is often referred as Application Context.


1 Answers

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().

like image 130
Yannic Klem Avatar answered Sep 22 '22 06:09

Yannic Klem