by BehindJava

How to display all the beans available in ApplicationContext in Spring Boot

Home » springboot » How to display all the beans available in ApplicationContext in Spring Boot

In this tutorial we are going to learn about displaying the beans that are loaded by the Spring Boot from the ApplicationContext. What we have to do is implement main class with CommandLineRunner/ApplicationRunner interface and override its run method.

CommandLineRunner/ApplicationRunner’s run() method will get execute right after ApplicationContext is created and before Spring Boot application initialized. This run() method will execute only once in an application’s life cycle. So what’s the difference between CommandLineRunner/ApplicationRunner? Basically, both will do the same trick, the only difference is CommandLineRunner’s run() method will accept String array and ApplicationRunner’s run() will accept ApplicationArguments as arguments.

SpringBootApp.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootApp implements CommandLineRunner {

    @Autowired
    private ApplicationContext context;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }

    @Override
    public void run(String...args) throws Exception {
        String[] beans = context.getBeanDefinitionNames();

        for (String bean: beans) {
            System.out.println(bean);
        }
    }
}

Output: Run the application and you will be able to see all the beans available in the context, here I am just adding few bean names from my console

...
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
requestMappingHandlerAdapter
requestMappingHandlerMapping
mvcValidator
mvcContentNegotiationManager
mvcPathMatcher
mvcUrlPathHelper
viewControllerHandlerMapping
beanNameHandlerMapping
resourceHandlerMapping
mvcResourceUrlProvider
defaultServletHandlerMapping
mvcConversionService
mvcUriComponentsContributor
httpRequestHandlerAdapter
simpleControllerHandlerAdapter
handlerExceptionResolver
mvcViewResolver
...
....