Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all the Spring beans that are loaded

Tags:

java

spring

Is there a way to print all the spring beans that are loaded on startup?I am using Spring 2.0.

like image 745
Punter Vicky Avatar asked Mar 07 '12 13:03

Punter Vicky


People also ask

How do you list all the beans in Spring?

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.

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.

How beans are loaded in Spring?

Spring Bean will be defined using stereotype annotations or XML Bean configurations. As soon as bean created and It will be instantiated and loaded into ApplicationContext and JVM memory. Spring container will create a bean id , scope , default values based on the bean definition.

What is the @bean annotation?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.


2 Answers

Yes, get ahold of ApplicationContext and call .getBeanDefinitionNames()

You can get the context by:

  • implementing ApplicationContextAware
  • injecting it with @Inject / @Autowired (after 2.5)
  • use WebApplicationContextUtils.getRequiredWebApplicationContext(..)

Related: You can also detect each bean's registration by registering a BeanPostprocessor bean. It will be notified for each bean.

like image 96
Bozho Avatar answered Sep 23 '22 06:09

Bozho


public class PrintBeans {     @Autowired     ApplicationContext applicationContext;      public void printBeans() {         System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));     } } 
like image 36
Akceptor Avatar answered Sep 22 '22 06:09

Akceptor