It can be useful, especially for debugging purposes, to list all the beans at a given moment.
We will use the code from the Defining a bean implicitly with @Component recipe, where we defined a UserService
bean.
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); }