Listing all beans
It can be useful, especially for debugging purposes, to list all the beans at a given moment.
Getting ready
We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService
bean.
How to do it…
Here are the steps to retrieve the names of the beans currently in Spring's ApplicationContext
object:
- In your class, add an
ApplicationContext
field annotated with@Autowired
:@Autowired private ApplicationContext applicationContext;
- In a method of that class, use
ApplicationContext
and itsgetBeanDefinitionNames()
method to get the list of bean names:String[] beans = applicationContext.getBeanDefinitionNames(); for (String bean : beans) { System.out.println(bean); }
How it works…
When the controller class is instantiated, Spring automatically initializes the @Autowired
field with its ApplicationContext
object. The ApplicationContext
object references all Spring beans, so we can get a list of all the beans that are using...