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 ...
Get Spring Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.