Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. In your class, add an ApplicationContext field annotated with @Autowired:

    @Autowired
    private ApplicationContext applicationContext;
  2. In a method of that class, use ApplicationContext and its getBeanDefinitionNames()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 it.

There's more…

To...